How to remove events that are created using Arrow Functions?

Asked

Viewed 73 times

1

Does anyone know if there is a way in Javascript to remove events that are created using Arrow Functions instead of creating a function for it? Example:

document.querySelector(element).addEventListener('click', (ev)=>{
  console.log('evento');
})

I wish to remove this created event, but how can I do it?

2 answers

3


Just you name the Arrow Function and use .removeEventListener where the second argument is the name given to the function

Instead of an anonymous function (ev)=>, put a name, like clique = (ev)=>.

let element = "#botao";
let clique; // declara a variável para o nome da função
document.querySelector(element).addEventListener('click', clique = (ev)=>{
  console.log("evento");
});

// esse listener abaixo é apenas para ilustrar o cancelamento do evento
document.querySelector("#cancelar").addEventListener('click', cancela = ()=>{
   // linhas de exemplo (apague)
   console.log("evento do botão cancelado");
   document.querySelector(element).textContent = "Clique-me e nada acontece :(";
   document.querySelector("#cancelar").textContent = "Evento foi cancelado";
   document.querySelector("#cancelar").removeEventListener('click', cancela);
   // fim das linhas de exemplo

   // remove o evento de clique no botão   
   document.querySelector(element).removeEventListener('click', clique);
});
<button id="botao">Clique-me</button>
<button id="cancelar">Cancelar evento</button>

2

If the element has more than one event for click (in this case), the interesting thing would be to identify them, but if it is only 1-1, you can simply remove all events associated with the element.

const events = getEventListeners(document.querySelector(element));
// check if exists a click event
events.click.forEach(ev => {
  document.querySelector(element).removeEventListener(ev.type, ev.listener)
});
  • 1

    That function getEventListeners does not exist in browsers, only on the Chrome console.

  • Poxa, knew not '-', it’s good to know that the console does not reflect 100% a javascript script

Browser other questions tagged

You are not signed in. Login or sign up in order to post.