Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone: firing an event only once on a Collection 'change'

Simple question: What is the best way to fire an event 'only once'?

I have a Collection in backbone with multiple models. Sometimes multiple models' attributes are updated at once, firing multiple 'change' events on the Collection.

What is the best way to fire the 'change' event only once, grouping all attribute changes together?

My best idea at the moment is using a timer but this will only capture the first model attribute change.

All suggestions, ideas and solutions are valued. Thank you :).


Context: In this case the event fires a very computationally intensive function, therefore multiple runs must be avoided.

like image 217
Dan0 Avatar asked Aug 09 '13 16:08

Dan0


2 Answers

Whenever you are updating the attributes on the models in bulk, pass {silent:true} as an option, which will suppress any events from being fired.

Then trigger a custom event for which a view or multiple views listening to the same.

like image 120
Sushanth -- Avatar answered Sep 22 '22 06:09

Sushanth --


You can "debounce" the method in your collection that responds to change events, though you'll have to manually figure out which models changed:

Col = Backbone.Collection.extend({
    modelChanged: _.debounce(function() {
        // handle model changes
    }, delayInMs),
    initialize: function() {
        this.collection.on('change', this.modelChanged, this);
    } 
})
like image 38
Stephen Thomas Avatar answered Sep 21 '22 06:09

Stephen Thomas