I’d like for a game to fire events upon key presses, but when I navigate away from and back to the game page the event listener fires twice. I found another issue suggesting I remove the listener before adding it, but that isn’t helping.
The listener is added during mounted
mounted() {
this.setupInputListener();
},
And the keydown event listener is added to the document
keydownListener() {
const action = handleKeyDown(event.key);
if ( action ) {
this.SEND_INPUT({
gameId: this.gameId,
action: action
});
}
},
setupInputListener() {
document.removeEventListener('keydown', this.keydownListener);
document.addEventListener('keydown', this.keydownListener);
}
How can I prevent this keydown listener from emitting duplicate events?