elemen.addEventListener('click',func,false);
elemen.addEventListener('click',func,false);
When elemen
is clicked, will the function func
be called twice, or just once?
If it is called twice, then is there a solution to check if the same event listener already exists on elemen
?
In your example, func
will not be called twice on click, no; but keep reading for details and a "gotcha."
From addEventListener
in the spec:
If multiple identical
EventListeners
are registered on the sameEventTarget
with the same parameters the duplicate instances are discarded. They do not cause theEventListener
to be called twice and since they are discarded they do not need to be removed with theremoveEventListener
method.
(My emphasis)
Here's an example:
const target = document.getElementById("target");
target.addEventListener("click", foo, false);
target.addEventListener("click", foo, false);
function foo() {
const p = document.createElement("p");
p.textContent = "This only appears once per click, but we registered the handler twice.";
document.body.appendChild(p);
}
<input type="button" id="target" value="Click Me">
It's important to note, though, that it has to be the same function, not just a function that does the same thing. That's because it works by looking for the function on the element's handler list, and two distinct functions — even if equivalent — aren't the same:
const f1 = () => {};
const f2 = () => {};
console.log(f1 === f2); // false
For example, here I'm hooking up four separate functions to the element, all of which will get called:
const target = document.getElementById("target");
for (let count = 0; count < 4; ++count) {
target.addEventListener("click", () => {
const p = document.createElement("p");
p.textContent = "This gets repeated.";
document.body.appendChild(p);
}, false);
}
<input type="button" id="target" value="Click Me">
That's because on every loop iteration, a different function is created (even though the code is the same).