I have a playGame() function that initiates an eventListener. Each time a new game is started, the playGame() function seems to create an additional eventListener. How can I remove the active eventListener so each time the game is played, so a new one is not added.
I have tried to use the removeEventListener as outlined here - https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener . I've also looked similar issues on stack overflow (like Removing event listeners before leaving a page ) but the solution there did not apply.
Here is how the function is laid out. I try to remove the old eventListener prior to loading the rest of the game scripts.
function playGame() {
console.log('new game');
// should remove event listener from previous game
document.removeEventListener('keyup', function() {userInput(activeStringObj, event.key);});
loadStartOutput();
wordPicker(activeStringObj);
addLetterDivs(activeStringObj);
addHint(activeStringObj);
document.addEventListener('keyup', function() {userInput(activeStringObj, event.key);});
}
I am logging the array that records the users key presses and it is obvious that multiple eventListeners are recording the inputs.
new game (typed 'a' 's')
game.js:98 ["a"]
game.js:98 (2) ["a", "s"]
new game (typed 'd' 'f')
game.js:98 (3) ["a", "s", "d"]
game.js:98 (4) ["a", "s", "d", "d"]
game.js:98 (5) ["a", "s", "d", "d", "f"]
game.js:98 (6) ["a", "s", "d", "d", "f", "f"]
new game (typed 'h' 'j')
game.js:98 (7) ["a", "s", "d", "d", "f", "f", "h"]
game.js:98 (8) ["a", "s", "d", "d", "f", "f", "h", "h"]
game.js:98 (9) ["a", "s", "d", "d", "f", "f", "h", "h", "h"]
game.js:98 (10) ["a", "s", "d", "d", "f", "f", "h", "h", "h", "j"]
game.js:98 (11) ["a", "s", "d", "d", "f", "f", "h", "h", "h", "j", "j"]
game.js:98 (12) ["a", "s", "d", "d", "f", "f", "h", "h", "h", "j", "j", "j"]
I am expecting only a single letter to be added to the array each time a key is pressed.