0

According to another stackoverflow question, "Are two functions equal?", it is impossible to verify if one function equals another.

This has me wondering how target.removeEventListener(type, listener) is implemented.

Observe my sample code:

function eventHandler() {
    alert("hello!");
    document.removeEventListener("click", eventHandler);
}
document.addEventListener("click", eventHandler);

When I click anywhere in the document an alert box will pop up and show me "hello!". When I dismiss the alert box and click anywhere in the document again, nothing happens.

I can of course register multiple listeners on the same target for the same event. I can even register multiple listeners with the same name.

How does it work?

Community
  • 1
  • 1
datcat
  • 143
  • 1
  • 1
  • 6
  • All you're doing here is throwing around a refernece to a function. There's no function comparison going on so I'm not sure what you're driving at. – Mitya Jul 19 '16 at 13:00

1 Answers1

1

You cannot tell if two different functions are equivalent, but you can tell if two variables reference the same function. These are 2 different concepts:

 function add(a,b) {
   return a+b;
 }
 function add2(a,b) {
   return a+b;
 }
    
 var myAddFn=add;
    
 console.log(myAddFn===add) //true
 console.log(myAddFn===add2) //false

Then, if the removeEventListener method has a list of event handlers for a given event, it can just go through them and removing the required one

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59