Sunday 7 October 2018

node.js: emitter.once(eventName, listener)

emitter.once(eventName, listener)
This method adds one-time listener to this event. Even though the event emitted more than one time, this listener called only once.

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

var emitter = new EventEmitter();

emitter.once('sayHello', (name) => {
 console.log("Hello mr.%s, How are you?", name);
});

/* Emitting 'sayHello' event 3 times */
emitter.emit('sayHello', "Krishna");
emitter.emit('sayHello', "Krishna");
emitter.emit('sayHello', "Krishna");


Output
Hello mr.Krishna, How are you?

Note
a.   This method returns a reference to the EventEmitter, so that calls can be chained.



Previous                                                 Next                                                 Home

No comments:

Post a Comment