Over a million developers have joined DZone.
Platinum Partner

EventEmitter in node.js

The Performance Zone is presented by AppDynamics. Scalability and better performance are constant concerns for the developer and operations manager. Try AppDynamics' fully-featured performance tool for Java, .NET, PHP, & Node.js.

Sometime back I had pawed at Making promises with javascript, but the node school of thought offers an attractive pattern of EventEmitters. 

EventEmitters are very much similar to PubSub, but are more tightly coupled and give more control.

I shall try to demonstrate these EventEmiters with few simple code snippets.

// Let's make a child ;)
var child = new (require('events').EventEmitter);
// Child's response 
child.once("born",function(){console.log("Say : Hello World!");});
child.on("cry",function(){console.log("The child is crying!");});
child.on("laugh",function(){console.log("Awe that is cute :)");});
//By default listener limit is 10, it can be increased using:
// Let the events emmit.
   // This wont execute 
   console.log("Born again!");
// Because birth is an one time event.

Output :

Say : Hello World!
The child is crying!
Awe that is cute :)

On a serious note, we can use this in a real programming scenario like :

if(error) emit("insertFailed",{err:err, customer:customer});  
else emit("added",customer);  

Anyway happy coding! Enjoy Emitting Events :)

The Performance Zone is presented by AppDynamics. AppDynamics is a leader in the APM space with massive cost reductions for users.


Published at DZone with permission of Hemanth Madhavarao , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}