Kyle Adams Kyle Adams - 7 months ago 11
Javascript Question

How would I pass in the current instance of this object to a ko computed observable?

Consider the following:

[ code removed. This is due to work asking for it to be removed and I have flagged this question for a moderator to close and delete. Please do not edit and put the code back ]

Now consider

session.loggedIn()
, The goal here is to say:
return this.idCode() > 0
how ever, because it is a closure, the reference to
this
is no longer the session object but the global window object. How can I bind this to the computed function such that, inside I can do:
return this.idCode() > 0
??

The catch? I need to be able to just call: session.loggedIn() and get true or false with out having to bind or do anything special "up front" It should all happen "behind the scenes". that is I should have to do anything like:
session.loggedIn().crazyBindingHereYo


This object is used by me doing:
var session = _DDCWidgetSession(ko, $, options);


Ideas?

Answer

The local variable session will always be acessible to any function created in the same (or nested) scope, even after the function returns.

var _DDCWidgetSession = function (ko, $, options) {
  var session = {
    loggedIn: ko.computed(function () {
      return session.idCode() > 0; // session will be acessible here since the function was created in the same scope.
    })
  }
  return session;
}

MDN - Javascript Closures