Wednesday 3 October 2018

EventEmitter: emitter.once(eventName, listener): Handle the event only once

emitter.once(eventName, listener)
There is situation, where you want to handle the event only once and ingore next events. You can achieve this using once method.

Below table summarizes the arguments of once method.
Argument
Type
Description
eventName
String
Name of the event
listener
Function
Callback function to be called on event emit.

Find the below working application.

HelloWorld.js
var events = require('events');

var emitter = new events.EventEmitter();

/* Register an event name 'myCustomEvent' */
emitter.once('myCustomEvent', (eventId, message) => {
    console.log(`Listener1: ${eventId} : ${message}`);
});

emitter.on('myCustomEvent', (eventId, message) => {
    console.log(`Listener2: ${eventId} : ${message}`);
});

/* Emit myCustomEvent */
emitter.emit('myCustomEvent', "demoEvent123", "Demo Application event");
emitter.emit('myCustomEvent', "demoEvent123", "Demo Application event");
emitter.emit('myCustomEvent', "demoEvent123", "Demo Application event");


As you see, I registered listener1 using once method, so it is called only once on event emit.

Output
Listener1: demoEvent123 : Demo Application event
Listener2: demoEvent123 : Demo Application event
Listener2: demoEvent123 : Demo Application event
Listener2: demoEvent123 : Demo Application event



Previous                                                 Next                                                 Home

No comments:

Post a Comment