When you look into the source code of Backbone.js, version 0.9.2, there is
“_onModelEvent”:
This method is responsible of forwarding events from the model to the collection (bubbling up).
So when you change something in a model which is part of a collection (with “set”), there is a change event, and because (in the add method) the _onModelEvent method was bound to the model (“all”), this method gets called.
I also see, that there is a destroy method, which triggers a “destroy” event.
But why does the author (in the first line of the _onModelEvent) check, if the event name is “add” or “remove”. Normally there is no “add” event on the model?
I do not understand this.
Can somebody explain it to me?
Thanks in advance
_onModelEvent: function(event, model, collection, options) {
if ((event == 'add' || event == 'remove') && collection != this) return;
With Backbone you can create nested model structures and collections. So you can create a collection where the model is a collection. That is way the check in place:
So from the annotated source:
So if you have a collection as a model. It won’t delegate the
addorremoveevent if items were added/removed to/from the child collections because in that case only the child collection is changed and not the parent.