gpt4 book ai didi

javascript - Backbonejs 如何在更改一个模型时设置集合中所有其他模型的属性

转载 作者:行者123 更新时间:2023-11-29 20:08:55 25 4
gpt4 key购买 nike

我有一个代表产品的模型(在 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});


});


});

最佳答案

集合中模型上的事件也是 triggered on the collection :

Backbone.Collection
[...]
Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience. This allows you to listen for changes to specific attributes in any model in a collection, for example: Documents.on("change:selected", ...)

因此您的集合可以简单地通过绑定(bind)到自身的 "change:active" 事件来监听来自其模型的 "change:active" 事件。然后它可以将其余模型本身设置为不活动:

var cs_products = Backbone.Collection.extend({
model: cs_product,
initialize: function() {
_.bindAll(this, 'propagate_active');
this.on('change:active', this.propagate_active);
},
propagate_active: function(p) {
if(!p.get('active'))
return;
this.each(function(m) {
if(p.id != m.id)
m.set({ active: false }, { silent: true });
});
}
});

演示:http://jsfiddle.net/ambiguous/WEkmy/


顺便说一句,没有理由自己跟踪集合中的模型:

var cs_products = Backbone.Collection.extend({
_products: [],
initialize: function(cs_products) {
this._products = cs_products; // <------------- ????
},
//...
});

集合是带有一些装饰的模型列表,所以所有这些都是烘焙的。您可以通过 this.models 访问模型数组。在集合中,或者您可以使用 baked-in Underscore methods迭代集合的模型。

关于javascript - Backbonejs 如何在更改一个模型时设置集合中所有其他模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10965253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com