Events
module provide support for asynchronous events. Events module provides
EventEmitter class, it implements pub-sub design pattern.
All
the node.js objects that emit events are the instance of EventEmitter claas.
Following
are the basic steps in event handling.
a. An EventEmitter
instance register listeners to an event
b. An eventEmitter
instance emit an event, once the event is emitted, correspondent listeners are
called synchronously.
Let
me explain with an example.
Step 1: Create an instance of
EventEmitter.
var
events = require('events');
var
emitter = new events.EventEmitter();
Step 2: Register to an event
emitter.on('myCustomEvent',
function(){
console.log("Custom Event
emitted");
});
Step 3: Emit the event.
emitter.emit('myCustomEvent');
When
the event is emitted, the function registered in step 2 is called.
var events = require('events'); var emitter = new events.EventEmitter(); /* Register an event name 'myCustomEvent' */ emitter.on('myCustomEvent', function(){ console.log("Custom Event emitted"); }); /* Emit myCustomEvent */ emitter.emit('myCustomEvent');
Output
Custom
Event emitted
A
listener function can take multiple arguments.
emitter.on('myCustomEvent',
function(eventId, message) {
console.log(`${eventId} : ${message}`);
});
You
can pass the arguments to listener function when emitting the event.
emitter.emit('myCustomEvent',
"demoEvent123", "Demo Application event");
var events = require('events'); var emitter = new events.EventEmitter(); /* Register an event name 'myCustomEvent' */ emitter.on('myCustomEvent', function(eventId, message) { console.log(`${eventId} : ${message}`); }); /* Emit myCustomEvent */ emitter.emit('myCustomEvent', "demoEvent123", "Demo Application event");
Output
demoEvent123
: Demo Application event
You
can add multiple listeners to an event using addListener method.
emitter.addListener('myCustomEvent',
(eventId, message) =>{
console.log(`Listener2: ${eventId} :
${message}`);
});
var events = require('events'); var emitter = new events.EventEmitter(); /* Register an event name 'myCustomEvent' */ emitter.on('myCustomEvent', function(eventId, message) { console.log(`Listener1: ${eventId} : ${message}`); }); emitter.addListener('myCustomEvent', (eventId, message) =>{ console.log(`Listener2: ${eventId} : ${message}`); }); emitter.addListener('myCustomEvent', (eventId, message) =>{ console.log(`Listener3: ${eventId} : ${message}`); }); /* Emit myCustomEvent */ emitter.emit('myCustomEvent', "demoEvent123", "Demo Application event");
Output
Listener1:
demoEvent123 : Demo Application event
Listener2:
demoEvent123 : Demo Application event
Listener3:
demoEvent123 : Demo Application event
No comments:
Post a Comment