0

我在多步骤向导中有一个ProductListView包含多个子视图的父视图。ProductView当用户单击 aProductView时,其模型的 id 应该存储在某个地方(可能在一个数组中),以便可以将其发送回服务器端进行处理。

问题:id我应该在哪里存储ProductView用户点击的?我尝试将其存储在其父视图中ProductListView,但似乎无法selectedProducts从子视图访问父视图中的数组ProductView

这是正确的方法吗?这应该怎么做?

模型

ProductCollection = Backbone.Collection.extend({
    model: Product,
    url: '/wizard'
});

父视图

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;
    }
});

子视图

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);
    }
});
4

2 回答 2

2

I don't think parent is a property of a backbone View type, and you haven't defined it, so there's no way this line is going to work:

this.parent.selectedProducts.push(this.model.id);

It seems like the correct approach would be to add a selected property to the Product model; toggle that property in the click handler. Then, when it's time to submit to the server, collect the IDs by filtering the Products collection for selected items (underscore.js included with Backbone makes this easy).

于 2012-09-03T02:37:43.600 回答
1

为什么不尝试直接在模型中保留选定的信息。那么,您将轻松跟踪所选使用事件的更改状态,并在进一步的向导步骤中使用该信息?

toggleSelection: function () {
    this.model.set({ selected: true });
}
于 2012-09-03T08:21:40.617 回答