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

176
Visualizações
How to manage event listeners that affects many elements in javascript

I'm new to JavaScript and was working through this tutorial: https://www.youtube.com/watch?v=i37KVt_IcXw

In it, a delete button is added to a list list elements, and an event listener is used to remove list elements when clicked (~10:30). Items in list with delete button

When setting up the event that removes list elements, it seems to me like there are two options:

  1. Add an event listener to each button
  2. Add an event listener to the list, track what is clicked, set up a rule for check the item, then remove it if the delete button is pressed.

Option 1 is very explicit, which I like. However, there might be a ton of event listeners that have to be managed, which isn't fun.

Option 2 is very concise, but we now have to be careful managing our conditions for selecting elements. If there are a lot of things we can click, the conditional could get out of hand, which isn't fun to maintain.

In the tutorial, they went with option 2 but didn't say way. Any are there any rules to consider for when to use each option? Are there any 3rd cleaner options I'm missing?

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

0

I go with option 1 for decades. Had no problem and I think it is more managable. Once you added event to delete you probably you won't need to remove it. Browser will handle memory and garbage collection job for you after a DOM element removed.

const deleteItem=function(event){
    if(!confirm('Are you sure ?')) return;
    //some business logic, requests etc...;
    //then remove DOM element
   this.parentElement.remove()
}
 
deleteBtn.addEventListener('click',deleteItem)

You can also use removeEventListener to remove the deleteItem event if ever needed.

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