building app in node : about event emitter and inheritance

for executing an event in node.js the code will be like this :

var events = require('events');

var eventEmitter = new events.EventEmitter();

eventEmitter.on('someOccurence', function(message){

eventEmitter.emit('someOccurence', 'Something happened!');

by using inheritance sys.inherit code will be like this .
the oop.js file will have

var sys = require('sys'),
 events = require('events');

function Downloader() {
 if(false === (this instanceof Downloader)) {
 return new Downloader();
sys.inherits(Downloader, events.EventEmitter); = function(episode) {
 var self = this;

 var statusMessage = 'Downloading: ' + episode;
 self.emit('status', statusMessage);    

 setTimeout(function() {
 var finishedMessage = 'Downloaded ' + episode;
 self.emit('finished', finishedMessage);
 }, 5000);

exports.Downloader = Downloader;

and in foo.js

var podcast = require("./oop");

var downloader = new podcast.Downloader();

downloader.on('status', function(message) {

downloader.on('finished', function(message) {
});'Astronomy podcast #89');

and while running output comese is node foo.js

Downloading: Astronomy podcast #89
Downloaded Astronomy podcast #89

Many of the inbuild module and third pary modules  uses the EventEmitter approach.

e.g. http module for requesting page on the web. and also for connect,disconnect,message.

References :

using call method :



About rahul23134654

Hi, I am Rahul Meha , B.E. in (I.T.)
This entry was posted in Node.js. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s