我在我的页面上有一块标记,表示一个视图,以及一个与该视图关联的JS控制器函数。(这些是Angular,但我不认为这很重要。) 控制器代码监听从应用程序中其他地方发出的自定义事件,并使用一些特定于控制器的逻辑处理该事件。
我的问题是控制器的事件处理程序被附加太多次了:每次重新激活视图时都会被附加,导致处理程序每次自定义事件被触发时都运行多次。我希望处理程序每次事件只运行一次。
我已经尝试使用.off()来解除绑定处理程序,然后再绑定它; 我已经尝试使用.one()来确保处理程序只运行一次; 我已经阅读了关于$.proxy()与.off()here交互的内容。
这里是我的代码草稿:
如何让它看起来像这样:
我的问题是控制器的事件处理程序被附加太多次了:每次重新激活视图时都会被附加,导致处理程序每次自定义事件被触发时都运行多次。我希望处理程序每次事件只运行一次。
我已经尝试使用.off()来解除绑定处理程序,然后再绑定它; 我已经尝试使用.one()来确保处理程序只运行一次; 我已经阅读了关于$.proxy()与.off()here交互的内容。
这里是我的代码草稿:
// 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
???
$(function() { ... })
中调用。 - rossipedia