Ana*_*nar 22 javascript backbone.js
我正在学习backbone.js,并对此感到困惑:我正在关注教程:http: //arturadib.com/hello-backbonejs/
正如您在第一个示例中所看到的(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);
Run Code Online (Sandbox Code Playgroud)
但是,如果我评论出这句话:_.bindAll(this, 'render');这仍然有效.我在谷歌搜索过,有人说这个方法bindAll()是必要的,因为如果我切换我的上下文,调用this.render可能不可用.我对"背景"感到困惑.当call(this.render)不可用时,还有人可以解释一下吗?
Den*_*ngo 29
对于您给出的示例_.bindAll(this, 'render');不是必需的,但如果您有this可能更改为其他内容的回调函数,那么_bindAll()可以很方便.
例如:
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 */
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*ons 10
bindAll
片段:
events: {
'click .win': 'win',
'click .lose': 'lose'
},
initialize: function () {
//win and lose are automatically bound for you
//because they are in the events property
//refresh must be manually bound
this.model.on('change', this.refresh);
//which you can do ECMA5 style if you like
this.model.on('change', this.refresh.bind(this));
//OR you can provide a context backbone style
this.model.on('change:foo', this.fooChange, this);
//However, since you pretty much never want an unbound function
//in a view, you can just stick this in all your initialize methods
//and call it done
//Note this will bind all functions in your view class if you don't
//pass specific method names. I recommend this form.
_.bindAll(this);
},
win: function () {...},
lose: function () {...},
refresh: function () {...},
fooChange: function() {...}
Run Code Online (Sandbox Code Playgroud)
... OOOOORRRR只需使用CoffeeScript和胖箭头,并在语言级别干净利落地解决这个问题.
| 归档时间: |
|
| 查看次数: |
14992 次 |
| 最近记录: |