javascript - 将 View 中的项目添加到数组 (backbone.js)

标签 javascript jquery backbone.js underscore.js

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

问题:我应该在哪里存储用户点击的ProductViewid?我尝试将其存储在其父 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/

相关文章:

javascript - Backbone.Marionette 和渲染嵌套结构

javascript - Backbone.js 的工作原理图?

如果表单中的元素少于一个,Javascript 将返回 'undefined'。

javascript - 文本区域 | val().length 在 chrome 中不计算 "Enter/Line Breaks"

javascript - 重试失败的 Jasmine 测试?

JQuery 数组逗号分隔值之和

javascript - 绑定(bind)子模型以在 Backbone /Marionette 中查看

javascript - jQuery-validate 不适用于 Kendo Button(包括 jsfiddle)

jquery - 如何: Zend_Form processing via ajax

jquery - 如何构建自定义 jQuery 缓动/弹跳动画?