I have a template like this:
<a class="btn btn-info btn-small edit" model-id="<%= model.id %>" href="">
<i class="icon-pencil icon-white"></i>
edit
</a>
And a view defined like this:
src.views.WinesView = Backbone.View.extend({
[...]
events: {
'click a.edit': 'edit'
},
edit: function(e) {
e.preventDefault();
var a = $(e.target);
var id = a.attr('model-id');
app.edit(id);
},
[...]
if the user clicks on the “edit” text, everything works fine, but if the users clicks on the icon-pencil icon (the content of the tag) the event is correctly raised, but e.target points to the i tag, and not to the a.
In fact, what I want is that if any tag inside the one I binded to tfires an event, I want that event to be raised and to easily get a reference to the element I binded from backbone…
I could solve it with:
edit: function(e) {
e.preventDefault();
var a = $(e.target);
if (a[0].tagName!=='A') { a = a.parent(); }
var id = a.attr('model-id');
app.edit(id);
},
but I was wondering if there’s a better, more elegant and generic way to achieve it…
Look into jQuery’s $.closest() method: