Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone reset event in collection

Tags:

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?

like image 549
user50992 Avatar asked Jul 13 '12 14:07

user50992


2 Answers

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.

like image 157
nikoshr Avatar answered Sep 29 '22 22:09

nikoshr


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.

like image 37
Paul Avatar answered Sep 29 '22 20:09

Paul