Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda