我有一个代表产品的模型(在 UL 中显示为 LI 项)和一个包含这些产品的集合。
当我单击一个 LI 时,我希望底层模型的属性设置为 true,并且集合中的所有其他模型的属性设置为 false。
//Model for product
var cs_product = Backbone.Model.extend({
defaults: function(){
return {
name: '',
active: false
};
},
initialize: function(){
if(!this.get('name'))
this.set({'name': this.defaults.name});
},
toggle: function(){
this.set({
active: !this.get('active')
});
}
});
//Collection of all products this user has access to
var cs_products = Backbone.Collection.extend({
_products: [],
initialize: function(cs_products){
this._products = cs_products
},
model: cs_product //<-- creates an instance of the cs_product model for each of our products
});
var user_client_products = new cs_products(globals.cs_user.cs_suite_products);
user_client_products.on('change:active', function(el, i, list){
console.log('collection change event');
console.log(arguments);
console.log(el.toJSON());
//loop over all models in collection and set active to false except for this?
this.each(function(el2){
if(el === el2)
return;
console.log(el2);
el.set({active: false});
});
});