我什么时候需要在Backbone.js的使用_.bindAll()? [英] When do I need to use _.bindAll() in Backbone.js?
问题描述
我学习Backbone.js的,感觉这个困惑:
我下面教程:
http://arturadib.com/hello-backbonejs/
I am learning backbone.js, and feel confused on this: I am following the tutorial : http://arturadib.com/hello-backbonejs/
,你可以在第一个例子中看到(1.js):
as you can see in the first example (1.js):
(function($){
var ListView = Backbone.View.extend({
el: $('body'), // attaches `this.el` to an existing element.
initialize: function(){
_.bindAll(this, 'render'); // fixes loss of context for 'this' within methods
this.render(); // not all views are self-rendering. This one is.
},
render: function(){
$(this.el).append("<ul> <li>hello world</li> </ul>");
}
});
var listView = new ListView();
})(jQuery);
但是,如果我注释掉了一句: _ bindAll(这一点,'渲染');
,这仍然可以工作。我曾在谷歌搜索,有人说,该方法 bindAll()
是必要的,因为如果我打开我的背景下,的this.render 调用code>可能不可用。我觉得在背景糊涂。也可能有人解释我当主叫(
this.render
)将不可用?
But if I comment out the sentence: _.bindAll(this, 'render');
, this will still work. I have searched in google and someone said that the method bindAll()
is necessary since if I switched my context, the calling of this.render
may unavailable. I feel confused on the "context". and also could some one explain me when the calling (this.render
) will unavailable?
推荐答案
有关你给的例子 _ bindAll(这一点,'渲染');
ISN ŧ必要的,但如果你有回调函数,其中这个
都不可能更改为别的东西的情况下,那么 _bindAll()
可以派上用场了。
For the example you've given _.bindAll(this, 'render');
isn't necessary but if you have callback functions where this
can possibly be changed to the context of something else, then _bindAll()
can be handy.
例如:
initialize: function(){
_.bindAll(this, 'render', 'clickFunc');
},
events: {
'click .someElement': 'clickFunc'
},
clickFunc: function(e) {
/** If you remove the clickFunc from the list of events in bindAll,
'this' will refer to the element that invoked the event.
Adding the clickFunc event in the _.bindAll, ensures that 'this' stays
as the view.
*/
this /** <-- our focal point */
}
这篇关于我什么时候需要在Backbone.js的使用_.bindAll()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!