我的页面中有一段代表视图的标记,以及与该视图关联的JS控制器函数。 (这些是Angular,但我不相信这个问题。)控制器代码监听从应用程序中其他地方触发的自定义事件,并使用某些特定于控制器的逻辑处理该事件。无法解除绑定jQuery自定义事件处理程序
我的问题是控制器的事件处理程序被连接了太多次:每次重新激活视图时都会连接,导致处理程序在每次自定义事件触发时都会运行多次。我只希望处理程序在每个事件中运行一次。
我已经尝试使用.off()
在绑定处理程序之前解除绑定处理程序;我试过.one()
以确保处理程序只运行一次;并且在阅读其与.off()
here的相互作用之后我试过$.proxy()
。
这里是我的代码草图:
// the code inside this controller is re-run every time its associated view is activated
function MyViewController() {
/* SNIP (lots of other controller code) */
function myCustomEventHandler() {
console.log('myCustomEventHandler has run');
// the code inside this handler requires the controller's scope
}
// Three variants of the same misbehaving event attachment logic follow:
// first attempt
$('body').off('myCustomEvent', myCustomEventHandler);
$('body').on('myCustomEvent', myCustomEventHandler);
// second attempt
$('body').one('myCustomEvent', myCustomEventHandler);
// third attempt
$('body').off('myCustomEvent', $.proxy(myCustomEventHandler, this));
$('body').on('myCustomEvent', $.proxy(myCustomEventHandler, this));
// all of these result in too many event attachments
};
// ...meanwhile, elsewhere in the app, this function is run after a certain user action
function MyEventSender() {
$('body').trigger('myCustomEvent');
console.log('myCustomEvent has been triggered');
};
点击左右在我的应用程序切换到麻烦视图五次,然后做它运行MyEventSender
动作后,我的控制台看起来就像这样:
myCustomEvent has been triggered
myCustomEventHandler has run
myCustomEventHandler has run
myCustomEventHandler has run
myCustomEventHandler has run
myCustomEventHandler has run
我怎样才能得到它看起来像这样:
myCustomEvent has been triggered
myCustomEventHandler has run
???
你可以让你的控制器不做任何事情,如果它不可见?没有修复你的bug,但它是一种解决问题的不同方式 – 2013-05-10 17:31:56
据我所知,Angular事件周期和jQuery事件周期完全不相关(除了它们都绑定到DOM之外)。您应该在'$(function(){...})'调用中将您的事件附加到控制器外部的
标记。 – rossipedia 2013-05-10 17:33:57适用于我:http://jsbin.com/adecul/1/edit – 2013-05-10 17:34:16