javascriptformsremoveeventlistener

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


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.