我正在研究一个包含ItemView
元素的ItemListView
的应用程序。在我的ItemListView
中,我使用jQuery .each()
方法遍历项目集合并将它们呈现为列表元素。在循环内的Backbone.js视图中访问方法
我已经完成了所有部分,除了将li
元素实际附加到包含ul
的元素之外。难点在于我的.each()
循环内部访问ItemListView.appendItem
方法。我试过使用this.appendItem
和self.appendItem
,但在循环内this
是item
和self
是window
对象。
这就是我现在所拥有的:
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;
我敢肯定,上下文问题是唯一的问题,因为我已经被他们输出到控制台,并检查了其他部分的这他们看起来很好。
我错过了什么?
哈,是你的
appendItem
功能将工作,忘了关于那个技巧。谢谢! – 2012-02-09 03:49:26把这个临时变量称为“那个”是很普遍的。 – knub 2012-02-09 12:00:52
然而,更好的做法是在@rfunduk发布的答案中正确设置上下文 – 2012-06-12 19:23:33