Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!