Backbone View event getting the proper target

♀尐吖头ヾ 提交于 2019-12-07 14:22:46

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10077961/backbone-view-event-getting-the-proper-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!