I have a collection x
(one instance) of models y
.
var y = Backbone.Model.extend({
defaults: {
name: null,
otherCollection: null
}
});
otherCollection
(multiple instances) is a collection of models z
.
Which event do I listen to inside collection x
so that I would get notified when any z
is added in / removed from otherCollection
?
Backbone by default only support event propagation from Contained Model
--> Containing Collection
. It won't do the sort of deep nested event propagation you're looking for without some extra effort.
To do it from Contained Collection
--> Containing Model
, you could do something like the following. Here we're setting up an EpisodeCollection
, which will be contained in a SeriesModel
. Whenever changes happen to the episode collection changes, we want to hear about it in the series:
var EpisodeCollection = Backbone.Collection.extend({
comparator: 'id'
// ... whatever you want
});
var SeriesModel = Backbone.Model.extend({
initialize: function() {
if (this.has('episodes')) {
this.listenTo(this.get('episodes'), 'all', this._onEpisodeChange);
}
},
_onEpisodeChange: function() {
var eventArgs = Array.prototype.slice.call(arguments, 1);
var eventName = arguments[0];
var toTrigger = 'change:episodes:' + eventName + ' change:episodes change';
this.trigger(toTrigger, eventArgs);
}
});
Here's a running JSFiddle illustrating this with a glorious Star Wars example:
http://jsfiddle.net/9kn6uqdn/4/
You can imagine building similar connections for deeper nesting as needed.
A great thing about Backbone is that it isn't an opinionated framework; it leaves the opinions to the application implementors (us!). To that end, I have tried deeply nested event propagation on a few different occasions, and each time have ended up going an alternative direction. Even in the simple example above, you can see that modifying the title
of Episode 6 actually fires 6 different events (which likely isn't what you expect).
You can improve this with more effort, but it can get startlingly complex very quickly. Event propagation in large apps can be hard to reason about, so in my mind the simpler the event flow the easier it is to manage & maintain.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments