获得正确目标的Backbone View事件

Mik*_*den 3 jquery event-handling backbone.js

给出以下简单的html:

<div class="someContainer">
  <h5>Some other information</h5>
</div>
Run Code Online (Sandbox Code Playgroud)

以下Backbone视图:

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

我发现自己做了以下一些代码,这对我来说似乎是一种代码味道.有什么我做错了或有更好的方法来做到这一点?

...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
 }
}
Run Code Online (Sandbox Code Playgroud)

这很有效,但我不确定这是编写无处不在的好代码.我可以制作一个我可以调用的方法,但我不确定它是否真正纠正了代码气味,它只是将其外包给其他地方.

mu *_*ort 9

你可以evt.currentTarget改用:

事件冒泡阶段中的当前DOM元素.

演示:http://jsfiddle.net/ambiguous/UgA5M/

或者你可以使用$container = $(evt.target).closest('.someContainer')而不用担心嵌套.

演示:http://jsfiddle.net/ambiguous/B49LG/

您使用哪种方法取决于您的具体情况.如果你在某种控件上有一个click处理程序,那么closest可能会更有意义; 如果你真的想要你绑定你的点击处理程序的元素(或者认为你有,那么这毕竟是基于delegate),然后使用currentTarget.