Home >>Nodejs Tutorial >Node.js - Event Emitter

Node.js - Event Emitter

Node.js - Event Emitter

EventEmitter Class

As we saw in the previous section, the EventEmitter class lies within the module for events. Accessible via the following code –

// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

When an instance of EventEmitter faces some mistake, it will emit a 'error' event. When a new listener is added, the event 'newListener' is fired, and the event 'removeListener' is fired when a listener is removed.

EventEmitter gives several properties such as on and emit. Binding feature to an event is used on the property and emitting is used to fire an event.

Sr No. Method Description
1 addListener(event, listener) Adds a listener to the stated event at the end of the listeners array. There are no searches done to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in multiple adds to the listener. Returns the emitter, so it can chain the calls.
2 on(event, listener) Adds a listener for the specified event at the end of the listeners array. There are no checks to see whether the listener has already been added. Multiple calls that pass the same combination of event and listener will result in multiple adds to the listener. Returns the emitter, so you can chain the calls.
3 once(event, listener) The event adds a one-time listener. Only the next time the event is fired, that listener is invoked, after which it is removed. Returns the emitter, so it can chain the calls.
4 removeListener(event, listener) Removes a listener for the specified event from the hearer array. Caution − The display indices in the listener array behind the listener are changed. RemoveListener will remove one listener instance from the listener array at most. If a single listener has been added to the listener array multiple times for the given event, removeListener must be called multiple times to remove. Returns the emitter, so it can chain the calls.
5 removeAllListeners([event]) Removes all listeners, except those of the event listed. It's not a good idea to remove listeners that have been added elsewhere in the code, especially when you didn't create it on an emitter (e.g. sockets or streams of files). Returns the emitter, so it can chain the calls.
6 setMaxListeners(n) By default, if more than 10 listeners are added for a given case, EventEmitters will print a alert. This is a useful default helping to identify memory leaks. Of course not every Emitter should be restricted to 10. This role allows for an improvement in that. Set for infinite, to zero.
7 listeners(event) Returns a listener array for the event you specify.
8 emit(event, [arg1], [arg2], [...]) Execute each of the listeners according to the arguments supplied. Returns true if listeners were present at the event, fake otherwise.

Class Methods

Sr. No Method Description
1 listenerCount(emitter, event) Returns listener numbers for a given event.

Events

Sr. No Events Description
1 newListener
  • event-String: the event name
  • listener−Function: the event handler function
Any time a listener is added to this event is emitted. When this event is triggered the listener may not have been added for the event to the listeners array yet.
2 removeListener
  • event − String The event name
  • listener − Function The event handler function

Any time someone removes a listener, this event is emitted. When triggering this event, the listener may not have been removed from the listeners array for the event yet.

Example

Make a js file named main.js with the following code − Node.js


var events1 = require('events');
var eventEmitter = new events1.EventEmitter();
// listener #1
var listner1 = function listner1() {
   console.log('listner1 executed.');
}
// listener #2
var listner2 = function listner2() {
   console.log('listner2 executed.');
}
// Bind the connection event with the listner1 function
eventEmitter.addListener('connection', listner1);
// Bind the connection event with the listner2 function
eventEmitter.on('connection', listner2);
var eventListeners = require('events').EventEmitter.listenerCount
   (eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
// Fire the connection event 
eventEmitter.emit('connection');
// Remove the binding of listner1 function
eventEmitter.removeListener('connection', listner1);
console.log("Listner1 will not listen now.");
// Fire the connection event 
eventEmitter.emit('connection');
eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
console.log("Program Ended.");

Run main.js now to see the result –
$ node main.js

Event Emitter