Javascript 在循环内部的Backbone.js视图上访问方法
我正在开发一个应用程序,它有一个Javascript 在循环内部的Backbone.js视图上访问方法,javascript,backbone.js,Javascript,Backbone.js,我正在开发一个应用程序,它有一个ItemListView,其中包含许多ItemView元素。在我的ItemListView中,我使用jQuery.each()方法循环遍历项目集合,并将它们呈现为列表元素 除了将li元素实际连接到包含ul的组件之外,我已将所有组件准备就绪。症结在于从我的.each()循环内部访问ItemListView.appendItem方法。我尝试过使用this.appendItem和self.appendItem,但在循环中,this是项,而self是窗口对象 以下是我现在
ItemListView
,其中包含许多ItemView
元素。在我的ItemListView
中,我使用jQuery.each()
方法循环遍历项目集合,并将它们呈现为列表元素
除了将li
元素实际连接到包含ul
的组件之外,我已将所有组件准备就绪。症结在于从我的.each()
循环内部访问ItemListView.appendItem
方法。我尝试过使用this.appendItem
和self.appendItem
,但在循环中,this
是项
,而self
是窗口
对象
以下是我现在拥有的:
ItemListView = Backbone.View.extend({
el: '#item-rows',
initialize: function () {
this.collection = new Items();
this.render();
},
render: function () {
$.each(this.collection.models, function (i, item) {
var itemview = new ItemView( { model: item });
this.appendItem(itemview); // this refers to the item, so appendItem is undefined
});
},
appendItem: function (itemView) {
$(this.el).append(itemView.render().el);
}
});
var itemlistview = new ItemListView;
我非常确定上下文问题是唯一的问题,因为我已经通过将它们输出到控制台来检查了其他部分,它们看起来很好
我遗漏了什么?是的,这是一个非常简单的解决方案。您只需在外部上下文中引用
这个
render: function () {
var somereftothis = this;
$.each(this.collection.models, function (i, item) {
var itemview = new ItemView( { model: item });
somereftothis.appendItem(itemview); // this refers to the item, so appendItem is undefined
});
},
要做到这一点,一个更重要的方法是使用集合的
每个,由underline.js提供:
render: function() {
this.collection.each( function( item, index ) {
var itemView = new ItemView( { model:item } );
this.appendItem( itemView );
}, this );
return this;
}
注:
- 请注意第二个参数to
each
,它引用函数绑定到
- 首先获取元素,然后获取索引
render
通常应返回this
以进行链接(如中所述),我认为如果没有此部分,appendItem
函数将无法正常工作
将临时变量称为“that”是一种常见做法,但更好的做法是按照@rfunduk发布的答案正确设置上下文