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

115
Visualizações
How can I remove dynamically generated event handlers in JavaScript

When I click the buttons, I see the console message showing that I've clicked them. When I uncheck the checkbox and then click the buttons, I expect no console messages but I still see them. Why doesn't the removeEventListener remove the event listener?

const buttons = document.querySelectorAll('ul li button');

function initialize() {
  for (let i = 0; i < buttons.length; i++) {
    function doSomething() {
      console.log(`You clicked on ${buttons[i].textContent}`);
    }

    if (document.querySelector('#mode').checked) {
      buttons[i].addEventListener('click', doSomething);
    } else {
      buttons[i].removeEventListener('click', doSomething);
    }
  }
}

document.querySelector('#mode').addEventListener('click', initialize);
initialize();
<input id='mode' type='checkbox' checked/>
<label for='mode'>Do something when you click</label>
<ul>
  <li><button>One</button>
  <li><button>Two</button>
  <li><button>Three</button>
  <li><button>Four</button>

I can't define doSomething outside of the for loop because I need i to do other stuff (not shown here for the sake of simplicity). I do need different handlers for each index.

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

0

Currently, doSomething is defined inside the for loop which means that every time initialize executes, you end up with a new function called doSomething. So addEventListener adds one function called doSomething, and removeEventListener attempts to remove a different function (also called doSomething). The new doSomething was never registered as an event listener so it can't be removed, and the old doSomething is out of scope so we can't reference it to remove it. Instead, you can dynamically generate the functions once and reference them in initialize.

const buttons = document.querySelectorAll('ul li button');

const buttonFunctions = [];

for (let i = 0; i < buttons.length; i++) {
  buttonFunctions[i] = function doSomething() {
    console.log(`You clicked on ${buttons[i].textContent}`);
  }
}



function initialize() {
  for (let i = 0; i < buttons.length; i++) {
    if (document.querySelector('#mode').checked) {
      buttons[i].addEventListener('click', buttonFunctions[i]);
    } else {
      buttons[i].removeEventListener('click', buttonFunctions[i]);
    }
  }
}

document.querySelector('#mode').addEventListener('click', initialize);
initialize();
<input id='mode' type='checkbox' checked/>
<label for='mode'>Do something when you click</label>
<ul>
  <li><button>One</button>
  <li><button>Two</button>
  <li><button>Three</button>
  <li><button>Four</button>

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