I have an application with a nested list I am trying to manage with backbone. there is a view for each individual <li> element, but each list element has it’s own nested <ul> tag, which has its own view instantiated. here is an example:
HTML
<ul class='elements'>
<li class='element'>
<div>
<a class='edit-element'>Edit</a>
</div>
<ul class='elements'>
<li class='element'>
<div>
<a class='edit-element'>Edit</a>
</div>
</li>
</ul>
</li>
</ul>
JavaScript
element_view = Backbone.view.extend({
events: {
'click .edit-element' : 'edit_element'
},
edit_element : function(event) {
//code to handle editing of an element
}
});
The issue is that if I click on a child element, both views will fire there edit_element event, which is problematic for several reasons. How can I structure this so that when I click a link in a child <li>, it fires for that <li>, and not any <li>s that contain it?
Backbone’s event handlers are just plain old jQuery event handlers so you can stop propagation in the usual ways using
stopPropagation:Demo: http://jsfiddle.net/ambiguous/Yb8rg/1/
Or by returning
false:Demo: http://jsfiddle.net/ambiguous/QvaGM/1/