SachiDangalla SachiDangalla - 16 days ago 6
Javascript Question

How to pass a Backbone function as a parameter

I have the requirement to pass a function in a Backbone view into another function in the same view. I used the following approach, which works fine for global functions. But when Backbone view instances are concerned, it does not work.

I believe the problem is that the passed function has incorrect context - note that

this
prints different objects in the console.

How to correctly pass the function and call the function in the correct context?

JSFiddle

//Backbone view
mainFunc: function(){
this.intermediateFunc(this.ABC);
}
intermediateFunc : function(callback){
console.log(this); //prints the correct view
callback();
}
ABC : function(){
console.log(this); //prints 'window' when passed through a function
}

Answer

The easiest thing would be to use Function.prototype.bind to bind the appropriate this to your function. Something like this:

mainFunc: function(){
    this.intermediateFunc(this.ABC.bind(this));
}

Another common approach with callbacks is to allow the caller to supply the desired this and Function.prototype.call or Function.prototype.apply to use it:

mainFunc: function(){
    this.intermediateFunc(this.ABC, this);
},
intermediateFunc : function(callback, context) {
    console.log(this); //prints the correct view
    if(context)
        callback.call(context);
    else
        callback();
}

Yet another approach would be to use the old var _this = this trick and pass an anonymous function to intermediateFunc:

mainFunc: function() {
    var _this = this;
    this.intermediateFunc(function() { return _this.ABC() });
}