JS:使用带参数的处理程序删除事件侦听器
JS: Removing event listeners with handlers that take arguments
我了解如何删除事件侦听器,但是,如果我想删除带参数的处理程序怎么办?
假设我有一个处理程序:
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);
我了解如何删除事件侦听器,但是,如果我想删除带参数的处理程序怎么办?
假设我有一个处理程序:
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);