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

175
Visualizações
pass the event and the element to the handler via event listener

I want to attach keypress event listener to each of words dom elements and pass the element itself ( I mean word) to the eventHandler ok?

So I tried this but it seems that I lose the event itself:

const eventHandler = (e, word) => {
    console.log('keypressed', String.fromCharCode(e.which), word);
}

words.forEach((word) => {
    window.addEventListener("keypress", eventHandler.bind(event, word));
}); 

String.fromCharCode(e.which) should bring the pressed key on keyboard but it returns nothing!!

How can I fix this?

Edit:

Here is the simpler reproduction of the issue: press any key on the keyboard and see the event is undefined:

const eventHandler = (event, word) => {
    console.log('keypressed', event, word);
}
window.addEventListener("keypress", eventHandler.bind(this, event, 'word'));

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

0

The event is implicitly passed, and will be the last parameter after all the bound parameters.

So you would use eventHandler.bind(null, word) and then the handler should be declared eventHandler(word, e) {...}

const button = document.getElementById('b');

function handler(bound_arg, event){
  console.log(event.target);
  console.log(bound_arg);
}

button.addEventListener('click', handler.bind(null,'bound'));
<button type='button' id='b'>Bound</button>

But this isn't very intuitive, and since bind() creates a new function anyway you could simply use an anonymous function to pass the word.

window.addEventListener("keypress", (e) => eventHandler(e, word));
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