Car*_*Lee 0 javascript backbone.js underscore.js
我正在学习本教程之后的 backbone.js ,但是我遇到了解第一个例子的问题:
(function($){
var ListView = Backbone.View.extend({
...
initialize: function(){
_.bindAll(this, 'render'); // fixes loss of context for 'this' within methods
this.render(); // not all views are self-rendering. This one is.
},
...
});
...
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
Q1:为什么要使用(function($){})(jQuery)
; 而不是完美的工作(function(){})();
?
Q2:怎么_.bindAll(this, 'render')
办?它如何修复方法中'this'的上下文丢失?
Q1:通过将jquery作为参数传递给你自己2件事:
Q2:bindAll
是来自Underscore.js的实用方法,它绑定this
特定方法 - 因此,当调用该方法(例如作为回调)时,this
将在其中使用正确的方法.
例如:
(function($){
var ListView = Backbone.View.extend({
...
initialize: function(){
// fixes loss of context for 'this' within methods
_.bindAll(this, 'render', 'makestuff');
this.render(); // not all views are self-rendering. This one is.
},
...
makestuff : function() {
...
this.stuff = ... // some action on the list's instance
}
});
...
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
在你的代码的某些部分,你做了类似的事情:
var list = new ListView({...});
$('#button').on('click', list.makestuff);
Run Code Online (Sandbox Code Playgroud)
this
in makestuff
方法是对上面的引用,list
而不是on
函数在其中makestuff
实际调用时所处的任何上下文.
实际实现依赖于使用apply
和call
函数将函数执行的上下文绑定到特定对象.