Reputation: 831
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.
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. I then tried
const myClicker = doThis.bind(this)
and then added and removed listener with myClicker variable, which also didnt work. Everytime I run
new myClass()
and click #div-1, a new listener is added and 'test' is printed not only one but many times...
Thanks in advance!
Upvotes: 0
Views: 296
Reputation: 241
If you define the listener with
myDiv.addEventListener('click', doThis, false)
The removal must contain all the same parameter you pass onto the 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
Upvotes: 1