2012-09-03 58 views
0

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

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

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

型号

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

回答

2

我不认为parent是骨干View类型的属性,而你还没有定义,所以没有办法此行是去工作:

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

这似乎是正确的做法是一个selected属性添加到Product模型;在点击处理程序中切换该属性。然后,在需要提交给服务器的时候,通过过滤Products集合中的选定项目(Backbone中包含的underscore.js使得这很简单)来收集ID。

+1

我也会采取@ dbaseman的方法,并让每个模型都有一个'selected'属性。然后在最后,您只需执行'collection.filter(function(product){return product.selected === true;})'来获取所选产品模型的数组。如果你愿意的话,你也可以很容易地'摘取()'ID。但骨干就这样,你推送数组的方式也没有错。只需将你的父视图引用给你的孩子。 'var childView = new ProductView({'parent':parentView});'你可以访问你的父视图数组。 – jmk2142

1

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

toggleSelection: function() { 
    this.model.set({ selected: true }); 
}