Created
August 8, 2012 22:04
-
-
Save jt2190/3299224 to your computer and use it in GitHub Desktop.
Example of EventEmitter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http') | |
, util = require('util') | |
, url = "http://www.thehubway.com/data/stations/bikeStations.xml" | |
, events = require('events'); | |
function handleError(e) { | |
console.error(e.message); | |
} | |
function ResponseDataListener(res) { | |
if (!(this instanceof ResponseDataListener)) { | |
return new ResponseDataListener(res); | |
} else { | |
events.EventEmitter.call(this); // call the super constructor first | |
this.data; | |
var self = this; | |
res.on('data', function(chunk) { | |
self.addChunk(chunk); | |
}) | |
res.on('end', function() { | |
self.emit('end', self.toString()); | |
}) | |
return this; | |
} | |
} | |
util.inherits(ResponseDataListener, events.EventEmitter); | |
ResponseDataListener.prototype.addChunk = function(chunk) { | |
this.data += chunk; | |
} | |
ResponseDataListener.prototype.toString = function() { | |
return this.data; | |
} | |
http.get(url, function(res) { | |
ResponseDataListener(res).on('end', function(s) { | |
console.log("*** markComplete ***"); | |
}); | |
res.on('error', handleError); | |
}).on('error', handleError); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment