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){
 console.log(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();
 }

 events.EventEmitter.call(this);
}
sys.inherits(Downloader, events.EventEmitter);

Downloader.prototype.download = 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) {
 console.log(message);
});

downloader.on('finished', function(message) {
 console.log(message);
});

downloader.download('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 socket.io for connect,disconnect,message.

References :

http://howtonode.org/demystifying-events-in-node

http://blog.nodejitsu.com/using-sys-inherits-in-node-js

http://nodejs.org/docs/v0.4.5/api/events.html#emitter.emit

http://elegantcode.com/2011/02/21/taking-baby-steps-with-node-js-implementing-events/

using call method :

http://elegantcode.com/2011/01/31/basic-javascript-part-9-reusing-methods-of-other-objects/

 

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s