Search code examples
javascripteventsbackbone.jscollectionsmodels

Same value on all models -> Collection event


Is it possible to have a Backbone Collection trigger an event when all the models in it have the same value assigned to a parameter?

For example all the models in a collection may start with :

model.value = false;

And i want the collection to trigger an event when all the models have

model.value = true;

Solution

  • By default backbone does not provide this as a feature, however you could check if all the models have the same attribute and then trigger a custom event.

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

    You would have to do this check each time you changed the "value" attribute.