removeEventListener not working when callback is bound to another object

谁说胖子不能爱 提交于 2020-01-14 02:57:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!