Over a million developers have joined DZone.

EventEmitter in node.js

· Performance Zone

Discover 50 of the latest mobile performance statistics with the Ultimate Guide to Digital Experience Monitoring, brought to you in partnership with Catchpoint.

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:
child.setMaxListeners(100);
 
// Let the events emmit.
child.emit("born");
child.emit("cry");
child.emit("laugh");
 
if(child.emit("born")){
   // This wont execute 
   console.log("Born again!");
}
// Because birth is an one time event.
console.log(child.emit("born"));

Output :

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

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

db.insert({...},function(err,Record){  
if(error) emit("insertFailed",{err:err, customer:customer});  
else emit("added",customer);  
}

Anyway happy coding! Enjoy Emitting Events :)



Is your APM strategy broken? This ebook explores the latest in Gartner research to help you learn how to close the end-user experience gap in APM, brought to you in partnership with Catchpoint.

Topics:

Published at DZone with permission of Hemanth HM, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}