Home > Net >  pass the event and the element to the handler via event listener
pass the event and the element to the handler via event listener

Time:09-21

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'));

CodePudding user response:

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));
  • Related