EventEmitter
is a class that helps us create a publisher-subscriber pattern in NodeJS.
With an event emitter, we can simply raise a new event from a different part of an application, and a listener will listen to the raised event and have some action performed for the event
Code your own event emitter in Node.js
node.js: emitter.rawListeners(eventName)
emitter.rawListeners(eventName)
This method returns a copy of the array of listeners for the event named eventName.
HelloWorld.js
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
var goodMorning = () => {
console.log('Good Morning');
}
var welcome = () => {
console.log('Welcome to node.js programming');
}
emitter.on('hello', goodMorning);
emitter.on('hello', welcome);
var listeners = emitter.rawListeners('hello');
for(index in listeners){
console.log(listeners[index]);
}
Output
[Function: goodMorning]
[Function: welcome]
emitter.removeAllListeners([eventName])
Removes all listeners, or those of the specified eventName
.
It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter
instance was created by some other component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter
, so that calls can be chained.
emitter.removeListener(eventName, listener)
Removes the specified listener
from the listener array for the event named eventName
removeListener()
will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName
, then removeListener()
must be called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener()
or removeAllListeners()
calls after emitting and before the last listener finishes execution will not remove them from emit()
in progress. Subsequent events behave as expected.
const EventEmitter = require("events");
class Emitter extends EventEmitter {}
const myE = new EventEmitter();
const m = () => {
console.log("listener");
};
myE.on("go", () => {
console.log("hello");
});
myE.on("dodo", () => {
console.log("hello");
});
myE.on("go", m);
myE.on("go", m);
console.log(myE);
myE.emit("go");
//output
/*
EventEmitter {
_events: [Object: null prototype] {
go: [ [Function (anonymous)], [Function: m], [Function: m] ],
dodo: [Function (anonymous)]
},
_eventsCount: 2,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
*/