0

I am new to Node.js and am having trouble debugging an issue. I have created an object which acts as an event emitter, however, my callbacks don't get called when the event is emitted.

I have defined my emitter as follows:

var EventEmitter = require('events').EventEmitter;
var util = require('util');

// this is the object which will inherit from EventEmitter
function RequestStreamReader() {
    EventEmitter.call(this);
}
util.inherits(RequestStreamReader, EventEmitter);
module.exports = RequestStreamReader;

RequestStreamReader.prototype.read = function(req) {
    var data = '';
    req.on('data', function(chunk){
        data += chunk;
    });
    req.on('end', function() {
        this.emit('readComplete', data);
    });
};

The code that consumes this module is listed below. The handler for my "readComplete" event does not execute despite the fact that this.emit(...) is called in the emitter (I have verified this in the debugger).

var Reader = require("../utils/requestStreamReader.js");

var reader = new Reader();
reader.on('readComplete', function(data){
    var userData = JSON.parse(data);
    var newUser = userModule.createFromDto(userData);
    userRepository.create(newUser, onSuccess, onFailure);
});
reader.read(req);

Any ideas on what I might be doing wrong?

Thanks!

Kartik
  • 160
  • 1
  • 7

1 Answers1

1

The reason is that "this" is not what you think it is in your code where you try to call this.emit('readComplete', data). In that context "this" refers to the callback function not the enclosing object. You need to do:

RequestStreamReader.prototype.read = function(req) {
    var data = '';
    var self = this;
    req.on('data', function(chunk){
        data += chunk;
    });
    req.on('end', function() {
        self.emit('readComplete', data);
    });
};

You can even see the same technique at work inside of the actual source to node.js itself: https://github.com/joyent/node/blob/master/lib/http.js#L80

ksimons
  • 3,797
  • 17
  • 17
  • Awesome thanks! I suspect this isn't the only time I'm going to run into problems caused by the `this` keyword. – Kartik Oct 20 '13 at 16:59
  • Pretty good overview here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – ksimons Oct 20 '13 at 17:02