Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
How can I stop this document attached event listener from emitting duplicate events?

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda