Node.js EventEmitter
To create and handle custom events Node.js uses events module. To create and handle custom events module EventEmitter class is used. Its syntax is given below.
const EventEmitter = require('events');
Event newListener is emitted when new listeners are added and when existing listeners are removed removeListener is emitted. Now let’s see an example.
// get the reference of EventEmitter class of events module
var events = require('events');
//create an object of EventEmitter class by using above reference
var em = new events.EventEmitter();
//Subscribe for FirstEvent
em.on('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
In this example we import the ‘events’ module and then create an object of the EventEmitter class. Then defines event handler function using on() function. Inside the on() method define name of event to handle and a callback function to call after an event is raised. An event can be raised even with no arguments.
var emitter = require('events').EventEmitter;
var em = new emitter();
//Subscribe FirstEvent
em.addListener('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
//Subscribe SecondEvent
em.on('SecondEvent', function (data) {
console.log('First subscriber: ' + data);
});
// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
// Raising SecondEvent
em.emit('SecondEvent', 'This is my second Node.js event emitter example.');
Comments
0 comments
Please Sign in or Create an account to Post Comments