Node js EventEmitter
Node js is event driven program. An event handler is called when some event is occurred. This event is same like a javascript event, like - event called on mouse click or on key press.
The eventEmitter class is used to bind event and event listener. Whenever an event get fired, there is a listener function start for executing. An instance of EventEmitter is created to listen and fire an event.
Multiple in-built events are available in Node js through the event module.
Example of EventEmitter
// get the events module
var events = require('events');
//create an object of EventEmitter class
var eventemitter = new EventEmitter();
//Assign the event handler to an event
eventemitter.on("eventname", function () {
console.log("event has occurred.");
});
//fire the event
eventemitter.emit("eventname");
console.log("Program Ended.");
List of all the important methods of EventEmitter class.
addListener(event, listener) | This method adds a listener at the end of the listeners array for the specified event. There is no check made to see if the listener has already been added. |
on(event, listener) | This method adds a listener at the end of the listeners array for the specified event. This method is an alias for addListener(event, listener). |
once(event, listener) | This method adds a one time listener to the event. The next time, when the event is triggered, this listener is removed and then invoked. It returns a reference to the EventEmitter, so that calls can be chained. |
removeListener(event, listener) | It removes a listener from the listener array for the specified event. The 'removeListener' event is emitted after the listener is removed. |
removeAllListeners([event]) | It removes all listeners from the specified event. It returns a reference to the EventEmitter, so that calls can be chained. |
setMaxListeners(n) | The setMaxListeners() method allows the limit of listeners to be modified for this specific EventEmitter instance, because by default, EventEmitters will print a warning if more than 10 listeners are added to a particular event. For unlimited number of listeners, this value can be set to '0' (Infinity). It returns a reference to the EventEmitter, so that calls can be chained. |
getMaxListeners() | The returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or default value. |
listeners(event) | It returns a copy of the array of listeners for the specified event. |
listenerCount(type) | It returns the number of listeners listening to the specified event. |
emit(event[, arg1][,..]) | It calls the each of the listeners in order with the supplied arguments. It returns true if the event had listeners, false otherwise. |