Unable to remove eventListener with removeEventListener

huangapple go评论56阅读模式
英文:

Unable to remove eventListener with removeEventListener

问题

I got problem with removing eventListener form function.

每次调用函数都会添加另一个事件,之后不会被移除。

我在控制台中使用以下代码进行检查:

getEventListeners(document.querySelector('body'));
function handleKeyDown(e) {
  const workoutEdit = document.querySelector('.formEdit');
  const backdrop = document.querySelector('.backdrop');
  if (e.key === 'Escape' && workoutEdit && backdrop) {
    curWorkout.parentElement.removeChild(workoutEdit);
    curWorkout.parentElement.removeChild(backdrop);
    body.removeEventListener('keydown', handleKeyDown);
  }
  if (e.key === 'Enter') {
    this.#workouts[indexWorkout].distance = +editDistance.value;
    this.#workouts[indexWorkout].duration = +editDuration.value;
    console.log(this.#workouts);
    body.removeEventListener('keydown', handleKeyDown);
  }
}

body.addEventListener('keydown', handleKeyDown.bind(this));
英文:

I got problem with removing eventListener form function.

Every call a function is adding another event and after that is not removed.

Im checking in console with:

getEventListeners(document.querySelector('body'));

function handleKeyDown(e) {
      const workoutEdit = document.querySelector('.formEdit');
      const backdrop = document.querySelector('.backdrop');
      if (e.key === 'Escape' && workoutEdit && backdrop) {
        curWorkout.parentElement.removeChild(workoutEdit);
        curWorkout.parentElement.removeChild(backdrop);
        body.removeEventListener('keydown', handleKeyDown);
      }
      if (e.key === 'Enter') {
        this.#workouts[indexWorkout].distance = +editDistance.value;
        this.#workouts[indexWorkout].duration = +editDuration.value;
        console.log(this.#workouts);
        body.removeEventListener('keydown', handleKeyDown);
      }
    }

    body.addEventListener('keydown', handleKeyDown.bind(this));

答案1

得分: 2

handleKeyDown.bind(this) 创建了一个新的函数,如果你不在某处存储对它的引用,它将无法通过removeEventListener()来移除。

如果需要绑定this,你应该像这样存储引用:

const boundHandler = handleKeyDown.bind(this);
body.addEventListener('keydown', boundHandler);

// 然后在某些情况下:
body.removeEventListener('keydown', boundHandler);
英文:

handleKeyDown.bind(this) creates a new function that can't be removed by removeEventListener() if you don't store the reference to it somewhere.

If you need to bind this, you should store the reference, like this:

const boundHandler = handleKeyDown.bind(this);
body.addEventListener('keydown', boundHandler);

// And then under some circumstances:
body.removeEventListener('keydown', boundHandler);

huangapple
  • 本文由 发表于 2023年3月31日 04:44:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892856.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定