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.
This line in
parseDataisn't doing what you expect:because, at that point,
thisis the global object. The problem occurs ingetDatawhen you set:Since you call
_cb()instead ofthis.parseData(),thisis not set correctly insideparseData. This is a common problem in JavaScript. You can either setselfin theServerfunction, which would give all methods declared inside there access to it, or you can bind it:which will cause
thisto be the right thing when_cbis called.