7
votes

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?

2

2 Answers

9
votes

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.

3
votes

You're correct that reset is fired after the old models have been removed and the new models have been added.

There isn't an event fired for when a model is removed from a collection through the reset method.

You might have to keep a reference to the old models outside of the collection, and then when the reset event is fired, you will have reference to those models so you can call the remove function for them on SVG.