Sunday 7 October 2018

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

emitter.on(eventName, listener)
It adds a listener to this event.

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

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

var emitter = new EventEmitter();

emitter.on('sayHello', () => {
 console.log("Hello World");
});

emitter.emit('sayHello');

Output
Hello World

You can add more than one listener to the event. ‘on’ method adds the listener function to the end of the listeners array for the event named eventName.

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

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

var emitter = new EventEmitter();

emitter.on('sayHello', () => {
 console.log("Hello World");
});

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

emitter.emit('sayHello', "Krishna");

Output
Hello World
Hello mr.Krishna, How are you?

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

b.   Event listeners are invoked in the order they called.


Previous                                                 Next                                                 Home

No comments:

Post a Comment