Share this blog!

How to pass Backbone function as a parameter

During the implementation of delete and clear container operations, I had to implement delete confirmation dialog boxes using Bootstrap Dialog. I thought of using a common confirmation function, which would take the action function as a parameter and call it if confirmed. (Note: jQuery's confirm provides similar functionality with the default dialog box)

I started by defining the following approach which works fine with global functions. But when Backbone view instances are concerned, it did not work. I assumed the problem was that the passed function has incorrect context - note that "this" prints different objects in the console.

var viewDemo = Backbone.View.extend({
    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
    }
});


As usual, StackOverflow came up with the solution when I asked this question. The solution of mu is too short explains 3 approaches:

1. Using Function.prototype.bind


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

2. Function.prototype.call or Function.prototype.apply


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();
}

Or the same could be used as:

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

3. The old var self = this; trick


mainFunc: function() {
    var _this = this;
    this.intermediateFunc(function() { return _this.ABC() });
}
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment