Mike Fielden
Mike Fielden

Reputation: 10153

Backbone View event getting the proper target

Given the following simple html:

<div class="someContainer">
  <h5>Some other information</h5>
</div>

And the following Backbone view:

var view = Backbone.View.extend({
  events: {
   'click .someContainer': performAction
  },
  performAction: function (evt) { 
    // Do things here
  } 
});

I find myself doing the following bit of code quite a bit and this seems 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
 }
}

This works, obviously but I'm not sure this is good code to write everywhere. I could make a method that I could just call but I'm not sure that actually corrects the code smell, it just outsources it somewhere else.

Upvotes: 3

Views: 3150

Answers (1)

mu is too short
mu is too short

Reputation: 434665

You could use evt.currentTarget instead:

The current DOM element within the event bubbling phase.

Demo: http://jsfiddle.net/ambiguous/UgA5M/

Or you could use $container = $(evt.target).closest('.someContainer') and not worry about the nesting.

Demo: http://jsfiddle.net/ambiguous/B49LG/

Which approach you use depends on your specific situation. If you have a click handler on a control of some sort, then closest might make more sense; if you really want the element that you've bound your click handler to (or think you have, this is all based on delegate after all), then use currentTarget.

Upvotes: 9

Related Questions