Backbone Dom Events Firing Multiple Times
Solution 1:
Since you omitted the selector in your events
object of your views the following applies
Per the Backbone Documentation:
Omitting the selector causes the event to be bound to the view's root element (this.el).
The problem is each of the SeriesGridItemView
's bind click
events to #model-grid
and each view is a child of #model-grid
. In your example, you register 5 click events and when you click on any of your views, all 5 events are triggered.
Without changing any of your other code, one solution is to setup you events
object to return a function so you can specify an id
selector for each of your views.
events: function() {
var selector = '#series-' + this.model.get('seriesId'); // this id corresponds to your template idvar ev = {};
ev['click ' + selector] = 'toggle';
return ev;
},
Another option and the one I prefer, is to not specify #model-grid
as your root element for all your views. It would end up looking like: demo
SeriesGridItemView = Backbone.View.extend({
// remove the following lineel:'#model-grid',
// .. all else is the same ../
});
series = newSeriesCollection(window.BMW.data.series);
series.forEach(function(m,i){
var c = i+1;
if(c > 3){
c%=3;
}
m.set('column','1');
$('#model-grid').append(newSeriesGridItemView({model:m}).el);
});
A side suggetion
In your
render
function, there's no need to create variable, you can access your element by using$
:render: function(){ this.template = _.template( $('#template-model-grid-item-view').html() ); this.$el.append(this.template(this.model.toJSON()))); }, setState: function(){ this.active = this.model.get('active'); this.$el.toggleClass('active',this.active); },
Post a Comment for "Backbone Dom Events Firing Multiple Times"