骨干查看活动得到适当的目标 [英] Backbone View event getting the proper target

查看:103
本文介绍了骨干查看活动得到适当的目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下简单的HTML:

Given the following simple html:

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

和下面的骨干观点:

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

我觉得自己做code以下位颇有几分,这似乎是一个code气味给我。是不是我做错了或有更好的方法来做到这一点?

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

这个工作,很明显,但我不知道这是好事code写的无处不在。我可以让我可以只调用一个方法,但我不知道,其实校正code气味,它只是外包到其他地方。

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.

推荐答案

您可以使用 evt.currentTarget 来代替:

You could use evt.currentTarget instead:

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

The current DOM element within the event bubbling phase.

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

或者你可以使用 $容器= $(evt.target).closest('。someContainer'),而不必担心嵌套。

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

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

哪种方法您使用取决于您的具体情况。如果你有某种形式的控制click处理,那么最接近可能更有意义;如果你真的想你已经绑定你的点击处理程序的元素(或认为你有,这是所有基于代表 毕竟),然后使用 currentTarget当前

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.

这篇关于骨干查看活动得到适当的目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆