获得正确目标的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
。
- 在Backbone渲染方法中调用jQuery插件
- jquery / jqueryui / jquerymobile在backbone.js应用程序中加载速度不够快
- jQuery IE9-10:无法获取undefined或null引用的属性替换
- 在JQuery移动UI中禁用散列更改控制器并替换为backbone.js
- Backbone.js将视图附加到多个元素
- Backbone / RequireJS嵌套列表中的循环依赖
- 在真实设备上的cordova app请求中出现net :: ERR_CONNECTION_TIMED_OUT错误
- Backbone.js Pushstate Routing和PHP Framework的路由器
- 向dom添加大量img元素时出现net :: ERR_INSUFFICIENT_RESOURCES错误