JS:删除带有接受参数的处理程序的事件侦听器

JS: Removing event listeners with handlers that take arguments

本文关键字:处理 程序 事件 侦听器 参数 删除 JS      更新时间:2023-09-26

我了解如何删除事件侦听器,但是,如果我想删除接受参数的处理程序该怎么办?

假设我有一个处理程序:

function handler(param1, param2){
    // do stuff with param1, param2
}

我通过包装器函数将上述处理程序添加到 DOM 节点

domNode.addEventListener("click", function(){
    // invoking the handler here with arguments
    handler(this.style.color, this.style.backgroundColor);
}

我如何删除上述听众的喜欢?

干杯

不能使用匿名函数。 您必须改用命名函数:

function callHandler(){
    // invoking the handler here with arguments
    handler(this.style.color, this.style.backgroundColor);
}
domNode.addEventListener("click", callHandler);

要删除它,您可以调用removeEventListener

domNode.removeEventListener('click', callHandler);