本文介绍了当回调绑定到另一个对象时,removeEventListener不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近注意到,当回调传递给绑定到另一个对象的 addEventListener 函数时,调用 removeEventListener

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.

示例:

/* '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)

我找到了使用默认功能<$的解决方法当您将对象传递给 addEventListener 时被调用的c $ c> handleEvent 。

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);
    }
  }
}

我写过。

但是,我是好奇为什么会这样?为什么 removeEventListener 找不到找到要删除的eventHandler?

But, I am curious about why is this happening? Why is that removeEventListener doesn't finds the eventHandler to remove it?

推荐答案

好的,我缺少的是 bind 总是返回一个新函数。这意味着我正在将一个不同的函数传递给 removeEventListener ,因此找不到将其删除的函数。

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.

这篇关于当回调绑定到另一个对象时,removeEventListener不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 09:36