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() }); }
0 comments:
Post a Comment