0

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));
  • If you have a function that dynamically creates additional event handlers that you keep having to remove, then maybe you should rethink the dynamically creating of events. Why are you creating more and more event handlers? – imvain2 Mar 30 '23 at 20:50
  • 1
    This is a guess, but I'd try removing the ``.bind(this)`` from ``addEventListener``. Perhaps ``removeEventListener()`` doesn't find the right event handler with that? – Dortimer Mar 30 '23 at 20:52
  • 2
    `bind` creates a new anonymous function, if you need to bind it, you'll have to store a reference to it to remove it. But I agree with @imvain2 , this looks like a situation for [event delegation](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) – pilchard Mar 30 '23 at 21:00
  • Does this answer your question? [Removing event listener which was added with bind](https://stackoverflow.com/questions/11565471/removing-event-listener-which-was-added-with-bind) – pilchard Mar 30 '23 at 21:25

1 Answers1

2

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);
Robo Robok
  • 21,132
  • 17
  • 68
  • 126