[JavaScript] How to Fix the Problem Where removeEventListener Cannot Remove Events

Tadashi Shigeoka ·  Tue, September 17, 2019

I’ll introduce a solution to the problem where events set with addEventListener in JavaScript cannot be removed with removeEventListener.

JavaScript

Background Knowledge - addEventListener, removeEventListener

Please check the following articles for the specifications of addEventListener and removeEventListener:

Case Where removeEventListener Cannot Remove Events

Case) Redefining the listener function

Code that cannot remove events

When touchmoveListener is defined inside onKeyDown, touchmoveListener gets redefined every time onKeyDown is called. Therefore, the touchmoveListener passed to addEventListener and the touchmoveListener passed to removeEventListener don’t point to the same function, so the event cannot be removed.

window.onload = () => {
  window.addEventListener('keydown', onKeyDown, false);
}

function onKeyDown(event) {
  function touchmoveListener(event) {
    event.preventDefault();
    console.log('handleTouchMove called');
  }

  if (event.key === 'Enter') {
    document.addEventListener('touchmove', touchmoveListener, { passive: false });
  } else if (event.key === 'Backspace' || event.key === 'Delete') {
    document.removeEventListener('touchmove', touchmoveListener, { passive: false });
  }
}

Code that can remove events

window.onload = () => {
  window.addEventListener('keydown', onKeyDown, false);
}

function touchmoveListener(event) {
  event.preventDefault();
  console.log('handleTouchMove called');
}

function onKeyDown(event) {
  if (event.key === 'Enter') {
    document.addEventListener('touchmove', touchmoveListener, { passive: false });
  } else if (event.key === 'Backspace' || event.key === 'Delete') {
    document.removeEventListener('touchmove', touchmoveListener, { passive: false });
  }
}

That’s all from the Gemba.