Highway View target acquisition event
Given the following simple html:
<div class="someContainer">
<h5>Some other information</h5>
</div>
And the following Backbone look:
var view = Backbone.View.extend({
events: {
'click .someContainer': performAction
},
performAction: function (evt) {
// Do things here
}
});
I find myself doing the next bit of code quite a bit and it looks like a code smell to me. Is there something I am doing wrong, or is there a better way to do this?
...performAction: function (evt) {
// Check to see if the evt.target that was clicked is the container and not the h5 (child)
if ($(evt.target).hasClass('someContainer')) {
// Everything is ok, the evt.target is the container
} else {
// the evt.target is NOT the container but the child element so...
var $container = $(evt.target).parent('.someContainer');
// At this point I now have the correct element I am looking for
}
}
It works, obviously, but I'm not sure if it's good code to write everywhere. I could make a method that I could just call, but I'm not sure what actually fixes the code smell, it just passes it somewhere else.
source to share
You can use instead evt.currentTarget
:
The current DOM element is in the bubbling phase of events.
Demo: http://jsfiddle.net/ambiguous/UgA5M/
Or you can use $container = $(evt.target).closest('.someContainer')
and not worry about nesting.
Demo: http://jsfiddle.net/ambiguous/B49LG/
Which approach you use depends on your specific situation. If you have a click handler on some control, it closest
might make more sense; if you really want the element associated with the click handler (or what you think is all based ondelegate
) then use currentTarget
.
source to share