title: JS bind the context of a function before passing
body: <p>I'm trying to setup a function that stores a callback which can be fired later on an event, but I'm not getting the context to bind right. The setup is basically like this:</p>
  
  <pre><code>app.myObject = function(){
    this.bindEvents();
  };
  app.myObject.prototype = {
    bindEvents: function(){
      var self = this;
      this.library = new OutsideLibrary();
      this.library.onMyEvent = function(data) {
        OtherLibrary.processData(data, self.runCallback); // I'm not able to pass a context here...
      }
    },
    sendToLibrary: function(message,callback) {
      this.callback = callback;
      this.library.send(message);
    }
    // ... and this doesn't work because it gets evaluated in the wrong context.
    runCallback: function() { 
      if (this.callback) {
        this.callback();
        this.callback = null;
      }
    }
  }
  </code></pre>
  
  <p>I hope the above code makes sense. The idea is, I'm trying to expose an API where I can call:</p>
  
  <pre><code>app.myObject.sendToLibrary("something", function() {...});
  </code></pre>
  
  <p>...and the callback function will run after the whole chain is complete.</p>
  
  <p>The problem is, I can't pass the callback that is received in <code>sendToLibrary</code> directly through, because the callback need to be passed to another object when an event fires. Also since I'm having to store the currently passed callback, and the callback is optional, I need to unset it once it has fired, so I actually need to pass the <code>runCallback</code> function to run the callback once then unset it.</p>
  
  <p>Anyway, the problem is that when <code>runCallback</code> eventually gets executed it is no longer in the correct context, so it doesn't work. My first idea for how to fix this was to change the <code>runCallback</code> function to include a context argument, so I could pass <code>self.runCallback(self)</code> -- but that executes immediately so it defeats the purpose.</p>
  
  <p>Anyway, I'm sort of lost in the callback woods here, and would appreciate some help finding my way out :)</p>
  
  <p>My question is: is there a way to wrap up a callback function and the correct context, without executing it now, so that when it eventually fires it does so from the correct context?</p>
  
  <p>Thanks!</p>