I'm trying to write a server, in nodejs, that can be called like so:
server.getData()
.on('complete', function(){
console.log('on complete triggered');
});
I'm trying to emit
the event from inside the callback for the response.end, inside the callback for the http.get. like so:
Server = function(){
events.EventEmitter.call(this);
this.getData = function(fn){
var _cb;
fn ? _cb=fn: _cb=this.parseData;
https.get('https://api.example.com', _cb);
return this;
}
this.parseData = function(resp, fn){
var _data = '';
var self = this;
resp.setEncoding('utf8');
resp.on( 'data', function(chunk){
_data += chunk;
});
resp.on( 'end', function(){
var j = JSON.parse(_data);
self.emit('complete');
console.log(j);
if(fn)
fn(j);
});
}
}
util.inherits(Server, events.EventEmitter);
server = new Server();
I'm lost as what to do. What is getting me is that I can access the _data
var in server.parseData
in resp.end
but I can't do the same for the server object.