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

244
Visualizações
javascript: how to call a code which will be called only once for an event

I want to run a code which will be called only once for an event. So, what will be the correct option(s)?

Option 1:

var EventSource = require("eventsource");
const source = new EventSource();

let callindex = 0;

source.once('event', () =>{
    console.log("called");
});
source.emit('event');

Option 2:

var EventSource = require("eventsource");
const source = new EventSource();

let callindex = 0;

source.on('event', () =>{
  if(callindex == 0){
    console.log("called");
  }
});
source.emit('event');

Option 3:

var EventSource = require("eventsource");
const source = new EventSource();

let callindex = 0;

source.on('event', () =>{
  if(callindex == 0){
    console.log("called");
  }
  callindex++;
});
source.emit('event');

Option 4

var EventSource = require("eventsource");
const source = new EventSource();

let callindex = 0;

source.on('event', () =>{
    console.log("called");
    source.removeAllListeners('event');
});
source.emit('event');
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Why do you need to use something like EventSource? Wouldn't standard Node suffice?

const handleCustomApplicationEvent = () => {
    console.log('hello');
    window.removeEventListener('application:event', handleCustomApplicationEvent, true);
}
window.addEventListener('application:event', handleCustomApplicationEvent, true);

/** trigger it */
const event = new CustomEvent('application:event');
window.dispatchEvent(event);

const event2 = new CustomEvent('application:event');
window.dispatchEvent(event2);

Notice that event2 will not be caught

---------------------- Edit ----------------------

The answer from @callmenikk is even better.

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