I'm writing a Marionette layout with three similar sub-layouts. Every o them is an instance of the same class. Here's the code:
Marionette.Layout.extend({
subCollection1: new SubCollection(),
subCollection2: new SubCollection(),
subCollection3: new SubCollection(),
initialize: function () {
this.subView1 = new subView ({
collection: this.subCollection1)
});
this.subView2 = new subView ({
collection: this.subCollection2)
});
this.subView1 = new subView ({
collection: this.subCollection3)
});
},
onRender: function() {
this.Reg1.show(this.subView1);
this.Reg2.show(this.subView2);
this.Reg3.show(this.subView3);
},
fetchColletions: function () {
this.subCollection1.fetch({ data: { /* some data for webserver */ } });
this.subCollection2.fetch({ data: { /* some data for webserver */ } });
this.subCollection3.fetch({ data: { /* some data for webserver */ } });
}
});
Then in my subLayout I'm binding function to collection request in initialize function like this:
Marionette.Layout.extend({
onCollectionRequest: function () {
console.log('summary.onCollectionRequest ' + this.cid);
//debugger;
},
initialize: function () {
this.listenTo(this.collection, 'request', this.onCollectionRequest);
}
});
The problem is, calling fetch on any of those collections triggers request events in all three collections so I get log like this:
fetchcollections
GET /* Server url */ 200 OK 157ms
onCollectionRequest view15
onCollectionRequest view24
onCollectionRequest view33
GET /* Server url */ 200 OK 332ms
onCollectionRequest view15
onCollectionRequest view24
onCollectionRequest view33
/* And so on for the third one */
Am I missing something? I always thought that event binding is per instance not per class. How should I address this?
P.S. My code is additionally wrapped in require.js define()
but I think it's irrelevant for my problem so I omitted it in code fragments.
Well, I've resolved my issue. It turns out I did a VERY bad thing in my App initializer. In order to have global fetch error handler I used 'on' function on prototype:
Backbone.Collection.prototype.on('error', fetchErrorHandler);
As also stated in How to add a default error handler to all Backbone models? it is a bad idea, beacause it creates global event handler for all collection instances in application. It causes every event handler is common for all collections which was excactly my issue.