javascript - 当处理程序需要接收回调函数时删除 jQuery 事件监听器

标签 javascript jquery

我有一个听众:

$(document).on("keypress", function(e){ebClose(e,mpClose)});

我正在尝试弄清楚如何动态删除它。挑战在于我真的希望 ebClos​​e 接收 mpClose 作为回调函数,因为在其他情况下 ebClos​​e 会接收不同的回调函数。

ebClos​​e 的作用是这样的:

function ebClose(e, callback){
    if (e.which == 13){
        callback();
    }
}

也就是说,它会检查它是否是 enter 键,然后调用回调函数。理论上,我可以制作 10 个不同版本的 ebClos​​e 并粘贴到不同的函数中以避免需要回调,但看起来代码很多。对于能够在需要时删除此监听器的策略有什么建议吗?

这显然行不通:

$(document).off("keypress", function(e){ebClose(e,mpClose)});

如果我把它改成这样:

$(document).on("keypress", ebClose);

然后我可以删除它,但不知道如何传递回调。感谢您的建议。

最佳答案

一个选项是 namespace the events .

Example Here

// Attach a keypress event namespaced to 'ebclose'
$(document).on("keypress.ebclose", function(e) {
  ebClose(e, mpClose)
});

// Remove the namespaced event:
$(document).off("keypress.ebclose");

或者,您也可以使用 $.proxy()绑定(bind)函数:

Example Here

$(document).on("keypress", $.proxy(ebClose, this, mpClose));

function ebClose(callback, e){
    if (e.which == 13){
        callback();
    }
}
function mpClose () {
    alert('Remove the event listener');
    $(document).off("keypress", $.proxy(ebClose, this, mpClose));
}

或者,类似地,您可以使用 .bind() method :

Example Here

$(document).on("keypress", ebClose.bind(this, mpClose));

function ebClose(callback, e){
    if (e.which == 13){
        callback();
    }
}
function mpClose () {
    alert('Remove the event listener');
    $(document).off("keypress", ebClose.bind(this, mpClose));
}

关于javascript - 当处理程序需要接收回调函数时删除 jQuery 事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33828496/

相关文章:

使用 Spring 3 MVC 和 jQuery 的 JSON 响应

JavaScript 函数 parseInt() 无法正确解析前导 0 的数字

javascript - 如何动态更新字段而不刷新且不占用服务器?

javascript - 我如何使用 jquery 读取简单的 json 结果以及如何发布新结果

javascript - 在两个div之间分割html?

jquery - Bootstrap 移动菜单调整到桌面

javascript - 从子范围到父范围的Angularjs ng-show不刷新

javascript - 在 IE8 中使用 JavaScript 在元标记后直接将 CSS 链接添加到 HEAD

javascript - 获取同级文本输入值

javascript - 在保存时添加 Logo 或水印