问题
I recently noticed that when a callback is passed to the addEventListener function that is bound to another object, calling removeEventListener later won't work.
Example:
/* 'this' is referencing e.g. a class */
element.addEventListener('click', this.clickHandler.bind(this))
/* the event listener won't be removed */
element.removeEventListener('click', this.clickHandler)
I found a workaround using the default function handleEvent that is being called when you pass an object to addEventListener.
/* 'this' is referencing e.g. a class */
element.addEventListener('click', this)
/* the event listener won't be removed */
element.removeEventListener('click', this)
this.handleEvent = function (e) {
switch(e.type) {
'click': {
this.clickHandler(e);
}
}
}
I wrote about it here.
But, I am curious about why is this happening? Why is that removeEventListener doesn't finds the eventHandler to remove it?
回答1:
Ok, something that I was missing is that bind always returns a new function. This means that I was passing a different function to removeEventListener thus it couldn't find it to remove it.
来源:https://stackoverflow.com/questions/41741642/removeeventlistener-not-working-when-callback-is-bound-to-another-object