How Do Event Listeners Work In Nodejs

Posted By : Abhinav Gupta | 29-Apr-2018

Understanding Events in Node

 

What are Events

    The whole of Node API works on events. Events are named strings that are emitted( i.e, can be accessed in any part of the node application) by any object of the EventEmitter Class. An object of the EventEmitter class exposes a function .emit('eventName', { associated data }), that allows us to emit an event with a name that we can choose, and also to send some data in the form of an object. An object of the EventEmitter class can be created in the following way
                        
                        var EventEmitter = require('events');
                        var emitter = new EventEmitter();

 

How are Events used
    
    Emitted events are responded to by eventListeners. These are functions that can be assigned to execute each time an event is emitted. They are "attached" to an event using the .on('eventName', function) method, exposed by an object of the EventEmitter class. The .on() method takes two arguments. The first argument is the eventName that has to be listened to, and the second argument is the function that is to be called when the event is emitted. Example:

 

                        emitter.on("anEvent", function(data){ console.log("anEvent was emitted with this data: ", data) });
                        emitter.emit("anEvent", { data: "strawberries" });


 

How are event listeners created

    An array containing all eventListeners is maintained by Node. It is called the listeners array. Each time .on() function is executed, a new event listener is added to that array. When the concerned event is emitted, each eventListener that is present in the array is called in a sequential or synchronous manner. This is one of the few places where we can see synchronous execution taking place in the Node API. The event listeners are called in a synchronous manner to avoid logical errors, race conditions etc. The total number of listeners that can be registered for a particular event, is controlled by a variable named maxListeners. It can be set using a function called .setMaxListeners(n). Where n is any number. The default number of listeners is 10. It is set by a variable named defaultMaxListeners.

 

                        emitter.setMaxlisteners(12);
                        

 

Managing Event Listeners

    As an event Listener once registered, exists throughout the life cycle of the program. It is important to detach an event Listener once its no longer needed to avoid memory leaks. Functions like .removeListener(), .removeAllListeners() enable the removal of listeners from the listeners Array.

About Author

Author Image
Abhinav Gupta

Abhinav is good at developing commercial software that save time and money. He is experienced with node.js and javascript.

Request for Proposal

Name is required

Comment is required

Sending message..