我有一个父 View ProductListView
,在多步骤向导中包含多个 subview ProductView
。当用户单击 ProductView
时,其模型的 id 应存储在某处(可能在数组中),以便可以将其发送回服务器端进行处理。
问题:我应该在哪里存储用户点击的ProductView
的id
?我尝试将其存储在其父 View ProductListView
中,但似乎无法从 subview ProductView
访问父 View 中的数组 selectedProducts
。
这是正确的方法吗?这应该如何完成?
型号
ProductCollection = Backbone.Collection.extend({
model: Product,
url: '/wizard'
});
家长 View
ProductListView = Backbone.View.extend({
el: '#photo_list',
selectedProducts: {}, // STORING SELECTED PRODUCTS IN THIS ARRAY
initialize: function() {
this.collection.bind('reset', this.render, this);
},
render: function() {
this.collection.each(function(product, index){
$(this.el).append(new ProductView({ model: product }).render().el);
}, this);
return this;
}
});
subview
ProductView = Backbone.View.extend({
tagname: 'div',
className: 'photo_box',
events: {
'click': 'toggleSelection'
},
template: _.template($('#tpl-PhotoListItemView').html()),
render: function() {
this.$el.html(this.template( this.model.toJSON() ));
return this;
},
// ADDS ITS MODEL'S ID TO ARRAY
toggleSelection: function() {
this.parent.selectedProducts.push(this.model.id);
console.log(this.parent.selectedProducts);
}
});
最佳答案
我不认为 parent
是主干 View
类型的属性,而且您还没有定义它,所以这条线无法工作:
this.parent.selectedProducts.push(this.model.id);
似乎正确的方法是向 Product
模型添加 selected
属性;在单击处理程序中切换该属性。然后,当需要提交到服务器时,通过过滤所选项目的 Products 集合来收集 ID(Backbone 中包含的 underscore.js 使这变得简单)。
关于javascript - 将 View 中的项目添加到数组 (backbone.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12241351/