Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removeEventListener - callback within function definition itself?

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?

like image 399
codingbryan Avatar asked Feb 24 '26 21:02

codingbryan


1 Answers

In the removeEventListener documentation we can see:

target.removeEventListener(type, listener[, options]);
target.removeEventListener(type, listener[, useCapture]);

...

listener
   The EventListener function 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.

like image 132
Christos Lytras Avatar answered Feb 27 '26 10:02

Christos Lytras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!