所有模型的值相同 - >集合事件



当骨干集合中的所有模型都为参数分配了相同的值时,是否可以让主干集合触发事件?

例如,集合中的所有模型都可能以 :

model.value = false;

我希望集合在所有模型都有时触发事件

model.value = true;

默认情况下,主干网不提供此功能,但是您可以检查所有模型是否具有相同的属性,然后触发自定义事件。

if(this.collection.length === this.collection.where({value: true}).length)
{
   this.collection.trigger('synchronized');
}

每次更改"value"属性时都必须执行此检查。

这是一种可能的方法:

// Model
var m = Backbone.Model.extend({
    initialize: function(){
        this.on("change", this.publish)
    },
    publish: function(){
        this.trigger("changed");
    }
});
// Collection
var c = Backbone.Collection.extend({
    model: m,
    initialize: function(){
        this.on("changed", this.check);
    },
    check: function(){
        console.log(this.length === this.where({value: true}).length);
    }
});
var m1 = new m();
var m2 = new m();
var c1 = new c([m1, m2]);
m1.set("value", true);
m2.set("value", true);

最新更新