Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

83
Vistas
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');
7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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.

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos