I noticed something odd with Backbone/Marionette. When I create an instance of a view that has a new collection property, then I create a nother instance of the view, its a new instance but the collection property points to the instance of the first view. See here:
var CollectionView = Marionette.CollectionView.extend({
collection: new Backbone.Collection()
});
var view = new CollectionView();
console.log('view is ', view);
view.collection.searchTerm = 'test';
console.log('view.collection is ', view.collection);
this.region.show(view);
var view2 = new CollectionView();
console.log('view2 is ', view2);
console.log('view2.collection is ', view2.collection);
this.region.show(view2);
You can see in the logs, there are 2 difference view instances (one has cid: "view2" and the other cid: "view5"). But the collection property of the second view has a property searchTerm
which is 'test'. I would have expected this to be a new Backbone collection....
Codepen is here.
It is expected behavior.
Collection is created only once, when you're calling extend
. All instances just have collection
reference in prototype of CollectionView
.
If you want your view instantiated with new collection every time, just create initialize
method:
var CollectionView = Marionette.CollectionView.extend({
initialize: function () {
this.collection = new Backbone.Collection();
}
});
var view = new CollectionView();
console.log('view is ', view);
view.collection.searchTerm = 'test';
console.log('view.collection is ', view.collection);
this.region.show(view);
var view2 = new CollectionView();
console.log('view2 is ', view2);
console.log('view2.collection is ', view2.collection);
this.region.show(view2);