[英]self.el vs this.el
我正在遵循一個ribs.js教程,並且遇到了2個函數initialize()
和render()
。 當附加一些html時, initialize()
使用$(self.el).append()
,而render()
使用$(this.el).append()
。 我對差異感到困惑,不勝感激,謝謝!
JS代碼
// Views
window.WineListView = Backbone.View.extend({
tagName:'ul',
initialize:function () {
this.model.bind("reset", this.render, this);
var self = this;
this.model.bind("add", function (wine) {
$(self.el).append(new WineListItemView({model:wine}).render().el);
});
},
render:function (eventName) {
_.each(this.model.models, function (wine) {
$(this.el).append(new WineListItemView({model:wine}).render().el);
}, this);
return this;
}
});
當事件觸發時范圍改變時,第一個使用self
來保持this
的引用。 在匿名函數內部(用於事件處理程序), this
將指向引發事件的元素,而不是您的Backbone控制器。
在第二種情況下不需要引用。
原因是JavaScript如何處理范圍。
在初始化函數中
var self = this;
因此,當他們將引用綁定到初始化的WineListView實例時,就調用了
this.model.bind("add", function (wine) {
$(self.el).append(new WineListItemView({model:wine}).render().el);
});
但是如果您將“ this”作為第三個參數發送,則可以在沒有自變量的情況下完成此操作。 第三個參數應規定應在其中調用回調的范圍
this.model.bind("add", function (wine) {
$(this.el).append(new WineListItemView({model:wine}).render().el);
}, this);
如果您查看那里的render is bind,它也使用第三個參數
this.model.bind("reset", this.render, this);
Disclamer我嘗試了該代碼,但是通過閱讀主干http://backbonejs.org/#FAQ-this上的文檔獲得了此代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.