Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

71
Views
removeListener dentro del bucle ES6

Tengo problemas para eliminar un oyente mouseover/mouseout dentro de un bucle foor. Digamos que tengo un menú que en el escritorio y al pasar el mouse muestra un menú desplegable, pero para abrir el menú desplegable lo quiero al hacer clic en el dispositivo móvil. Necesito eliminar el desplazamiento en el móvil porque no quiero que haga ambas cosas. Aquí está mi función principal que abre el menú desplegable:

 addChildrenActive(i){ if(this.parent[i].classList.contains('b--nav-a__list-group__list-item--is-active')){ //removes class to hide the dropdown } else { //adds class to show the dropdown } }
  • tenga en cuenta que esta función recibe i como parámetro.

por otro lado, tengo la función responsable de los oyentes:

 navbarInteraction(){ if(this.isMobile){ //calculated via another function based on breakpoints that returns true for (let i = 0; i < this.parent.length; i++) { this.parent[i].addEventListener('click', e => { e.preventDefault(); this.addChildrenActive(i) }); this.parent[i].removeEventListener('mouseover', this.addChildrenActive(i)); this.parent[i].removeEventListener('mouseout', this.addChildrenActive(i)); } } else { for (let i = 0; i < this.parent.length; i++) { this.parent[i].addEventListener('mouseover', e => { this.addChildrenActive(i) }); this.parent[i].addEventListener('mouseout', e => { this.addChildrenActive(i) }); } } }

RemoveEventListeners cuando isMobile no funciona para mí y actualmente puedo desplazarme y hacer clic para mostrar el menú desplegable. ¿Cómo debo resolver esto?

¡Gracias por adelantado!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Como @Teemu indicó, debe usar una función con nombre porque necesita una referencia a esa función si desea eliminarla de un oyente.

Entonces, en lugar de escribir una función anónima dentro de addEventListener() , le proporciona el nombre de una función que definió en otro lugar, y lo más importante, no dentro de su bucle.

Por ejemplo:

 parent[i].addEventListener('mouseover', e => { this.addChildrenActive(i) });

se convierte

 parent[i].addEventListener('mouseover', mouseOverHandler);

y se llama funcion

 function mouseOverHandler(e) { console.log("mouse over", e.currentTarget); }

Es posible que haya notado el parámetro e dentro de la función. Esto se completará con datos relacionados con el evento, por ejemplo, el nombre del evento o qué elemento lo causó.

Este oyente se puede eliminar usando:

 parent[i].removeEventListener('mouseover', mouseOverHandler);

Déjame darte un ejemplo más completo:

 class Navigation { constructor() { this.isMobile = false; this.parent = document.querySelectorAll("div"); this.navbarInteraction(); } navbarInteraction() { for (let i = 0; i < this.parent.length; i++) { this.parent[i].removeEventListener('mouseover', this.addChildrenActive); this.parent[i].removeEventListener('click', this.addChildrenActive); if (this.isMobile) { this.parent[i].addEventListener('click', this.addChildrenActive); } else { this.parent[i].addEventListener('mouseover', this.addChildrenActive); } } } addChildrenActive(e) { console.log("addChildrenActive()", e.currentTarget, e.type); } } let navigation = new Navigation();
 <div id="divA">DIV1</div> <div id="divB">DIV2</div> <input type="checkbox" onchange="navigation.isMobile=this.checked;navigation.navbarInteraction();"> <span>isMobile</span>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!