How to avoid duplicate Javascript addeventlistener calls?

Asked

Viewed 55 times

3

I would like to add an event to several different classes, example:

exemplo1.addEventListener('click', function(){
    //Evento bla bla
});

exemplo2.addEventListener('click', function(){
    //Evento bla bla
});

exemplo3.addEventListener('click', function(){
    //Evento bla bla
});

And in order not to create duplicate code, I’d like to transform that Event in something like:

exemplo1.eventExample();
exemplo2.eventExample();
exemplo3.eventExample();

This eventExample would have the:

addEventListener('click', function(){
    //Evento bla bla
});

I apologize if I used any wrong term, I’m starting in programming!

I know I could create a function with the same event code and play inside the others Event listeners, but I wanted to learn that way.

1 answer

3


If you add event listeners in Javascript, you add one at a time. Because there is no addEventListeners, only addEventListener (in the singular).

This duplication is rarely problematic, but if you really want to get rid of it, you can create an array with the elements to receive the Listener and iterate on them by adding individually in a single row. The caveat is that you will share the same Handler among them all, but this seems to be the requirement of the question.

Something like that:

function eventHandler(event) {
  // Faça algo aqui.
}

[example1, example2, example3].forEach((example) =>
  example.addEventListener('click', eventHandler));

See a functional example:

const el1 = document.getElementById('el-1');
const el2 = document.getElementById('el-2');

function eventHandler(event) {
  console.log('Clicou em:', event.currentTarget.textContent);
}

[el1, el2].forEach((el) =>
  el.addEventListener('click', eventHandler));
<a href="#" id="el-1">Clique! (a tag)</a>
<button id="el-2">Clique! (button tag)</button>

You can also find there "recommendations" to modify the prototype of NodeList (or similar constructor) aiming at the addition of a new method (such as addEventListeners), but this is rarely necessary and is not even a good idea, since it can bring problems. I explain them in more detail here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.