Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling removeEventListener does not work

I don‘t understand why removeEventListner() is not working in my code.
Below is my code with simplified names etc.:

const form = document.querySelector(".formclass")

function executeUserInput(userInput){
  function sayHello(event){
    event.preventDefault()
    console.log("Hello")
  }

  if(userInput === "add"){
    form.addEventListener("submit", sayHello)
  }else{
    form.removeEventListener("submit", sayHello)
  }
}

When I execute this code, and trigger condition1 and else-part multiple times, an eventlistener is added every time I trigger condition1 but the removeEventListener does not remove it. When inspecting in google Dev tools I can also see that the submit listener exists after else-part was executed.
Why?
I did find some questions about this issue on stackoverflow, but none of them helped me

Updated the code to represent my code more precisely, hope this clarifies

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The .removeEventListener() method makes a direct comparison between the function object you pass to it and all the other registered event handler function objects. If the function you pass is not a registered handler, then it won’t do anything.

In this case, you’ve got a function declared inside that outer function. That means that each time the outer function is called, a new version of the inner event handler is created. If one call to the outer function adds a handler, and the next call should remove the handler, it won’t have a reference to the handler function created on the previous call.

Try moving the handler function to outside that outer function (executeUserInput()).

Another thing this will cause is if you call the outer function 3 times in a row, and the condition is always true, you’ll get 3 separate event handlers on the form.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading