Backbone reset event in collection

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

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?

回答1:

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.



回答2:

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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!