繁体   English   中英

如何删除咖喱事件侦听器

[英]How to remove a curried Event Listener

我有一个使用 curried 函数的addEventListener ,所以我可以使用函数的参数。

const curryFunction = (product) => {
  return function curry(e) {
    //do stuff here
  }
}

const addEvent = (product) => {
  document.getElementById('button').addEventListener('click', curryFunction(product))
}

但我希望能够删除它,我在堆栈溢出时查找了与此类似的问题,但由于他们没有这种特定情况,他们似乎没有工作。 我试过了

document.getElementById('button').removeEventListener('click', curryFunction(product)) // just didn't do anything
document.getElementById('button').removeEventListener('click', curryFunction()) // gave me error
document.getElementById('button').removeEventListener('click', curry()) // gave me error

以及相似之处,例如

document.getElementById('button').removeEventListener('click', curryFunction)
document.getElementById('button').removeEventListener('click', curryFunction(product))//this one was nested inside a function so I wouldn't get an error || product had the same value as the product in the addEvent(product)
document.getElementById('button').removeEventListener('click', curry)
document.getElementById('button').removeEventListener('click', curry(e))//this one was nested inside a function so I wouldn't get an error with the e

他们都没有工作,那么有什么方法可以做

  1. 删除 curried eventListener 函数或
  2. 有一个没有.bind()的 eventListener 因为那也不起作用

问题是removeEventListener需要引用相同的确切“对象”,因为它将使用对象标识来查看要删除的侦听器。

curryFunction函数每次调用时都会创建一个新实例,因此您必须跟踪该函数以便稍后将其删除:

var myListener = undefined;
const addEvent = (product) => {
  // Store the reference to the listener somewhere
  myListener = curryFunction(product);
  document.getElementById('button').addEventListener('click', myListener)

}

// later on use myListener to remove the listener

document.getElementById('button').removeEventListener('click', myListener)

请注意,在这种情况下,如果两次调用addEvent而不调用removeEventListener ,您将丢失引用。 因此,要么您应该在添加新的侦听器之前检查您还没有一个/删除现有的侦听器,或者您可以使用数组/对象同时跟踪多个侦听器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM