javascript - 无法取消绑定(bind) jQuery 自定义事件处理程序

标签 javascript jquery angularjs

我的页面中有一 block 表示 View 的标记,以及与该 View 关联的 JS Controller 函数。 (这些是 Angular,但我认为这并不重要。) Controller 代码监听从应用程序中其他位置触发的自定义事件,并使用一些特定于 Controller 的逻辑处理该事件。

我的问题是 Controller 的事件处理程序附加太多次:每次重新激活 View 时它都会附加,导致每次触发自定义事件时处理程序都会运行多次。我只希望处理程序每​​个事件运行一次。

我尝试在绑定(bind)处理程序之前使用 .off() 取消绑定(bind)处理程序;我尝试过 .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');
};

在我的应用程序中单击并切换到麻烦的 View 五次,然后执行运行 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

???

最佳答案

为您的事件提供一个命名空间,然后在重新运行 Controller 时简单地删除具有该命名空间的所有事件。

jsbin

$('body').off('.controller');
$('body').on('myCustomEvent.controller', myCustomEventHandler);

关于javascript - 无法取消绑定(bind) jQuery 自定义事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16487790/

相关文章:

javascript - $(document.body).css 不工作

javascript - `?` 在某些对象属性之前是什么意思?为什么我的 ts 文件不接受它?

javascript - SJCL "Cannot read property ' 替换“未定义”的问题

javascript - 如何获取活跃等级值?

javascript - 在移动设备上向下滚动时菜单关闭

javascript - 获取双重嵌套 JSON 响应解析 Javascript API

javascript - 可以访问 ng-repeat 创建的范围项吗?

javascript - javascript 可以有多少行?

javascript - 如何验证背景(css)图像是否已加载?

css - 删除空白区域是 SELECT angular app IE-CSS