Backbone.js: how to unbind from events, on model remove

后端 未结 3 1979
执念已碎
执念已碎 2020-12-15 12:42

in backbone we have an app that uses an event Aggregator, located on the window.App.Events now, in many views, we bind to that aggregator, and i manually wrote

3条回答
  •  太阳男子
    2020-12-15 13:35

    Instead of wrapping Collection's reset with cleanUp as fguillen suggested, I prefer extending Collection and overriding reset directly. The reason is that cleanUp takes effect only in client's code, but not in library(i.e. Backbone)'s. For example, Collection.fetch may internally call Collection.reset. Unless modifying the Backbone's source code, we cannot unbind models from events(as in cleanUp) after calling Collection.fetch.

    Basically, my suggested snippet is as follows:

    var MyCollection = Backbone.Collection.extend({
            reset: function(models, options) {
                this.each(function(model) {
                    model.unlink(); // same as fguillen's code
                });
                Backbone.Collection.prototype.reset.apply(this, arguments);
            }
        });
    

    Later, we can create new collections based on MyCollection.

提交回复
热议问题