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?
You cannot add an event listener multiple times, that will cause it to fire once or many times. To avoid this, try using onkeydown. Once we do this we no longer need the removeEventListener. For example, something like this should work:
keydownListener() {
const action = handleKeyDown(event.key);
if (action) {
this.SEND_INPUT({
gameId: this.gameId,
action: action
});
}
},
setupInputListener() {
document.onkeydown = () => {
this.keydownListener;
}
}
Hoped this helped!