获得正确目标的Backbone View事件

给出以下简单的html:

Some other information

以下Backbone视图:

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

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

 ...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 } } 

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

您可以使用evt.currentTarget代替:

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

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

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

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

您使用哪种方法取决于您的具体情况。 如果你在某种控件上有一个单击处理程序,那么closest可能更有意义; 如果你真的想要你绑定你的点击处理程序的元素(或者你认为已经完全基于delegate ),那么使用currentTarget