I have a Backbone app that uses nested collections (at least that\'s how I think they\'re called).
In my particular case there are tabs
A change
event is triggered by Backbone when an attribute changes via set
. The event is then also triggered on the collection, as you have seen. But, the value of your subtabs
attribute is not changing at all, it is still the same object you created in defaults
. If you used tab.set('subtabs', new Subtabs);
you would get a change:subtabs
event, but you don't want to do that.
I think you would have to do something in your code to trigger a new event on your Tab model.
// Tab Model
var Tab = Backbone.Model.extend({
defaults: { label: undefined, subtabs: new Subtabs},
initialize: function(){
// listen for change in subtabs collection.
this.get('subtabs').on('change', this.subtabsChanged, this);
},
subtabsChanged: function(model) {
// trigger new event.
this.trigger('subtab:change', this, model);
}
});
Then you could listen for the event:
tabs.on('subtab:change', function(tab, subtab) {
console.log(tab.get('label'));
console.log(subtab.get('label'));
});
This will work, I think. But I guess I am wondering why you would listen to your Tabs collection for a change in the Subtabs. In most cases, it might be better to just listen for the change event on your Subtabs collection itself.
tab.get('subtabs').on('change', function(model){
// do something with model, which is a Subtab.
});
EDIT: http://jsfiddle.net/phoenecke/DvHqH/1/