Reputation: 773
I have app where one type of view is nested in same type. Something like this http://take.ms/ylAeq
How can I catch event on view button and fired event on proper view?
I have situation when I have ~10 fired events becuase backbone binds event to all inner buttons, not only button of proper view.
I have one idea - I make in template id="node_body_<%= id %>"
so each button id based on it's view's model id; but how can I pass it to events object? events :{ "click #node_body_" + id : 'method' }
doesn't work.
Upvotes: 0
Views: 60
Reputation: 43156
The issue is event bubbling. The events on your inner view's bubble upto the el
of it's parent view's, which is listening for events on same selector, in turn triggering it's handler.
This can be fixed by stopping the propagation of event in the respective view's handler:
Backbone.View.extend({
events: {
'click .thing': 'do_thing'
},
do_thing: function(event) {
event.stopPropagation(); // prevents event reaching parent view
}
});
Upvotes: 1
Reputation: 434616
Most properties of Backbone views can be functions instead of literal values. For example, these two things have the same result:
Backbone.View.extend({
events: {
'click .thing': 'do_thing'
},
do_thing: function() { ... }
});
and
Backbone.View.extend({
events: function() {
return {
'click .thing': 'do_thing'
};
},
do_thing: function() { ... }
});
So if your events
depend on properties of the view, then you'd want to use a function instead of an object literal:
events: function() {
var events = { };
var event_spec = 'click #nody_body' + this.id;
events[event_spec] = 'method';
return events;
}
That assumes that id
is the property of the view that you're using in your template.
Upvotes: 0