Force Closure ...

Force Closure ...

In recent times I've started using class libraries in Javascript, which is great, but I've noticed with signal handlers and callback routines there's an unintuitive trap I keep falling into, which is that callback routines don't carry a context.

This can be a royal pain and when I first came across it, my immediate reaction was to try to carry the context either via the callback, or via some sort of global message passing object.

Must have been a Coffee shortage at the time ...

Anyway, when it dawned on me that Closures made all these issues just "go away", I have to wonder why every tutorial doesn't start with .. "and don't forget that any callbacks need to be closures to make sure you don't lose context .." (or maybe they do and I should read more tutorials?)

For example, take my first approach;

var CLASS = CLASS || {};
JS.require('JS.Class',function(Class){
  CLASS.MyClass = new Class({
    class_var: "Instance Variable",
    initialize: function() {
      session.call('this.is.my.topic',{text:'Hello'},this.success)
    },
    success: function(data) {
        console.log("Data>",data);
        console.log("Classvar>",this.class_var);
    }
  });
});

Now this appears to work, and it sort of looks like it should be right, but it's not right and whatever it prints against "Classvar", it won't be what you want. The solution, just shuffle the code around a little to create a closure;

var CLASS = CLASS || {};
JS.require('JS.Class',function(Class){
  CLASS.MyClass = new Class({
    class_var: "Instance Variable",
    initialize: function() {
      var _this = this;
      var success = function(data) {
        console.log("Data>",data);
        console.log("Classvar>",_this.class_var);
      }
      session.call('this.is.my.topic',{text:'Hello'},this.success)
    },
  });
});

So all of a sudden, your callback routine, instead of being called as a singleton with no context, is called as a first class method of the object you actually want it to reference. Magic!

If this is obvious to you, call me an idiot and move on .. but otherwise, read it again, there's shed load of mileage in that-there concept ...