Question

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.

Was it helpful?

Solution

This line in parseData isn't doing what you expect:

var self = this;

because, at that point, this is the global object. The problem occurs in getData when you set:

_cb=this.parseData

Since you call _cb() instead of this.parseData(), this is not set correctly inside parseData. This is a common problem in JavaScript. You can either set self in the Server function, which would give all methods declared inside there access to it, or you can bind it:

_cb=this.parseData.bind(this)

which will cause this to be the right thing when _cb is called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top