Backbone reset event in collection

backbone.js

How does Backbone reset event works?
As far as I understand

  1. Remove all models from collection
  2. Add newly "fetched" models to collection
  3. Fires reset event

In my case each model draw something on SVG so I should call remove function before removing model from collection. Which event is triggered when model is removed from collection?

Best Answer

As @Paul noted, there is no predefined event fired before a reset. However, you can provide your own by overriding the reset method on your collection. For example,

var SVGCollection = Backbone.Collection.extend({
    reset: function(models, options) {
        options = options || {};

        if (!options.silent) {
            this.trigger('prereset', this, options);
        }

        Backbone.Collection.prototype.reset.call(this, models, options);
    }
});

And a sample usage

var c = new SVGCollection([
    {id: 1},
    {id: 2}
]);
c.on('prereset', function() {
    console.log(c.pluck('id'));
});
c.on('reset', function() {
    console.log(c.pluck('id'));
});
c.reset({id: 3});

See http://jsfiddle.net/nikoshr/8vV7Y/ for a demo

You could also trigger events on each model.

Related Topic