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

138
Visualizações
.removeEventListener(); by name or reference?

Say you have simple:

document.removeEventListener('click', clickHandler);

Does removeEventListener remove a registered listener for click events named clickHandler or does it remove a registered listener for click events referencing the very same function that clickHandler references?

Here they say:

The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process

When they say "the event listener function itself", do they mean the very same reference?

I'm asking because I have (in a React project) a memoized function that removes a bunch of event listeners and I would like to know how often I need to get a new function.

If removeEventListener removes handlers by names, I can leave the dependecy array of useCallback empty.
But if removeEventListener removes by references, I need to put all the listeners in the dependency array. And maybe I would be better off without memoization.

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

0

In your example clickHandler is an identifier. Identifiers can't be converted to strings, so there is no way for JavaScript to remember if the same identifier name has been used as an argument before. They are merely names meant to be read by developers.

So yes, you will need to pass the reference to the function. Even if you pass that reference via another identifier.

function clickHandler() {
  console.log('Clicked!');
}

const buttonElement = document.querySelector('button');

buttonElement.addEventListener('click', clickHandler);

setTimeout(() => {
  const differentHandlerName = clickHandler;
  buttonElement.removeEventListener('click', differentHandlerName);
  console.log('Removed event listener via a different identifier name');
}, 2000);
<button>
  Click
</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

You must pass a reference to the same function used for addEventListener when calling removeEventListener

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