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
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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Abhinav Gupta
Abhinav is good at developing commercial software that save time and money. He is experienced with node.js and javascript.