I am running into an issue where I'm adding to a collection, CollectionA
, where CollectionA
and CollectionB
are listening for an add event. However, an add event is triggered for both collections when adding to CollectionA
. CollectionA
and CollectionB
are basic collections that extend Backbone.Collection
and only setting a url.
View Definitions
ModelViewA = Backbone.View.extend({
...
render : function() {
var self = this;
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
var collectionB = new CollectionB();
var collectionViewB = new CollectionViewB();
collectionB.fetch({
self.$el.append(collectionViewB.render().el);
});
return this;
},
...
});
CollectionViewA = Backbone.View.extend({
initialize : function() {
this.collection.on('add', this.renderOne, this);
},
...
render : function() {
this.collection.forEach(this.renderOne, this);
return this;
},
renderOne : function(model) {
console.log('Added to Collection A');
var view = new ViewA({ model : model });
this.$el.append(view.render().el);
return this;
}
});
CollectionViewB = Backbone.View.extend({
initialize : function() {
this.collection.on('add', this.renderOne, this);
},
...
render : function() {
this.collection.forEach(this.renderOne, this);
return this;
},
renderOne : function(model) {
console.log('Added to Collection B');
var view = new ViewB({ model : model });
this.$el.append(view.render().el);
return this;
}
});
Here's how I'm starting off the cascade of these events...
var collectionA = new CollectionA();
var modelViewA = new ModelViewA({
model : collectionA.at('some id');
});
$('body').append(modelViewA.render().el);
$('body').empty();
var collectionViewA = new CollectionViewA({ collection: collectionA });
$('body').append(collectionViewA.render().el);
collectionViewA.add([{...}]);
This code will output the initial view correctly with the modelView. Then it will properly render the collectionViewA
, however when I trigger the add event it will try to add to CollectionA
and CollectionB
so the console will show the following for each time the add event is called
Added to Collection B
Added to Collection A
It will also attempt to render Collection B
, but throws an error because the template is not given a model.
Let me know if this is way too confusing and I can try to flush out this description a bit more.
THANKS!