简体   繁体   English

由 JavaScript 中的 Class 实例添加的 RemoveEventListener

[英]RemoveEventListener added by Class instance in JavaScript

I am having difficulties (actually have run out of ideas) on how to remove event listener from my div-element, which is added every time I generate a new instance of Class.我在如何从我的 div 元素中删除事件侦听器时遇到困难(实际上已经没有想法了),每次生成 Class 的新实例时都会添加该事件侦听器。

class myClass {

myFunc () {
    const myDiv= document.querySelector('#div-1')
    myDiv.addEventListener('click', doThis, false)

   function doThis () {
   console.log('Test')
    }
   }
}

I have so far tried到目前为止我已经尝试过

myDiv.removeEventListener('click', doThis)

before adding a new eventListener, which I guess doesnt work, because it doesnt have a reference to the specific instance and function in question.在添加一个新的 eventListener 之前,我猜这不起作用,因为它没有对特定实例和 function 的引用。 I then tried然后我尝试了

const myClicker = doThis.bind(this)

and then added and removed listener with myClicker variable, which also didnt work.然后使用 myClicker 变量添加和删除侦听器,这也不起作用。 Everytime I run每次我跑

new myClass()

and click #div-1, a new listener is added and 'test' is printed not only one but many times...并单击#div-1,添加了一个新的侦听器,并且“test”不仅打印了一次,而且打印了很多次...

Thanks in advance!提前致谢!

If you define the listener with如果您使用以下方式定义侦听器

myDiv.addEventListener('click', doThis, false)

The removal must contain all the same parameter you pass onto the addListener删除必须包含您传递给 addListener 的所有相同参数

// Make sure to include the 'false' parameter
myDiv.removeEventListener('click', doThis,false)

source: https://developer.mozilla.org/pt-BR/docs/Web/API/EventTarget/removeEventListener来源: https://developer.mozilla.org/pt-BR/docs/Web/API/EventTarget/removeEventListener

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

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