Hello. Ever since the new certifications were announced, I’ve been going on a journey to earn the legacy front-end, just for fun before it possibly forever vanishes.
Right now I’m working with the Simon game.
However, I’m having some issues with the button’s event listeners, which appear to remain persistent even after I call removeEventListener()
To recreate the bug, just start the game, score the first point, click reset and start the game again, score the first point, and look in the console
The project is below. Help would really be appreciated.
If you’re unsure whether a listener is attached, log or inspect it during runtime.
Do not use anonymous functions directly in addEventListener. Always assign them to a variable or constant first.
If you’re working with dynamic elements or frameworks, ensure you track and clean up listeners when elements are removed from the DOM.
Use once: true in the event listener options if you only need the listener to trigger once:
Your issue likely arises because the event listener functions are being redefined every time you call the cycle function. This creates a new function reference for registerBlueClick, registerRedClick, etc., which prevents removeEventListener from removing the previously attached listeners.
In JavaScript, removeEventListener works only if the function reference provided is exactly the same as the one used with addEventListener. Since you’re redefining registerBlueClick and others each time cycle is called, the previous listeners remain active.
Define the event listener functions only once at the top level, outside of cycle.
Use these predefined functions for both addEventListener and removeEventListener.