I have the following code where I add an event listener to the document and then remove it.
document.addEventListener("keypress", gameStart);
function gameStart() {
document.querySelector("h1").innerHTML = "Level 1";
document.querySelector("h2").style.visibility = "hidden";
document.removeEventListener("keypress", gameStart);
}
I cannot wrap my head around how I can have a callback to gameStart in the removeEventListener method inside the definition of gameStart() itself. This seems circular to me, but I sense I am misunderstanding something fundamental here. What am I missing?
In the removeEventListener documentation we can see:
target.removeEventListener(type, listener[, options]); target.removeEventListener(type, listener[, useCapture]);...
listener
TheEventListenerfunction of the event handler to remove from the event target.
the EventListener function (in your case gameStart) is not called when calling removeEventListener, therefore there is not any circular calling or recursion, it is passed to removeEventListener so this function can be unregistered from that event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With