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

197
Visualizações
javascript one eventlistener to rule them all vs multiple listeners (best practice)

Hi I have been looking on the internet trying to figure out the best practice for adding eventlistener to my websites and it generally comes down with two approaches as follow:

Adding an event listener to every elements (e.g. button) using a loop:

document.querySelectorAll('.some-button').forEach(item => {
    item.addEventListener('click', event => {
        //handle click
    })
})

Or using event bubbling to use one listener only and check the e.target for each scenario:

body.addEventListener('click', event => {
    if (event.target !== element1 && event.target !== element2) {
        //return
    }
    //handle click
}

However, I was unable to find any article comparing the performance of these 2 approaches. From my limited understanding, whenever there is a 'click' javascript will loop through all the eventlisteners anyway (even though if you didn't click on it) and for that reason I am taking the second approach (using one eventlistener) which seems to be the easier one to manage.

Appreciate if someone can provide further insights on the potential drawback of the second approach and if there will be any performance issue thanks.

about 4 years ago · Juan Pablo Isaza
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