Backbone View事件获取正确的目标 [英] Backbone View event getting the proper target
问题描述
鉴于以下简单的html:
Given the following simple html:
<div class="someContainer">
<h5>Some other information</h5>
</div>
以下Backbone视图:
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.
推荐答案
您可以使用 evt.currentTarget
代替:
You could use evt.currentTarget
instead:
事件冒泡阶段当前的DOM元素。
The current DOM element within the event bubbling phase.
演示: http://jsfiddle.net/ambiguous/UgA5M /
或者你可以使用 $ container = $(evt.target).closest('。someContainer')
而不用担心嵌套。
Or you could use $container = $(evt.target).closest('.someContainer')
and not worry about the nesting.
演示: http://jsfiddle.net/ambiguous/B49LG/
您使用的方法取决于您的具体情况。如果您有某种控件上的点击处理程序,则最接近
可能会更有意义;如果你真的想要你绑定你的点击处理程序的元素(或者认为你有,这都是基于委托
),然后使用 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
.
这篇关于Backbone View事件获取正确的目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!