I have stripped the problem back to the following code:
var EventEmitter = require("events").EventEmitter,
util = require('util');
function Foo() {
EventEmitter.call(this);
}
util.inherits(Foo, EventEmitter);
Foo.prototype.on('hello', function() {
console.log("World");
});
Foo.prototype.start = function() {
console.log('Hello');
this.emit('hello');
}
var foo = new Foo();
foo.start();
Using Node v0.10.36 this code outputs:
Hello
World
However using Node v0.12.1 the code outputs:
Hello
It appears the the listener is no longer functioning in the later version of Node.
This is part of a module, that is exported / required, so I'm trying to keep the listeners away from an instance of the module.
Can anyone explain why this stopped working, and what is the recommended way to do this.
You can't put a .on()
handler on the prototype like you are doing. The EventEmitter
part of your object doesn't even know it's there and no event handler has been registered with the EventEmitter
base object.
Instead, you need to install the event handler AFTER you've instantiated the object so that the EventEmitter
has a chance to actually register the event handler.
var EventEmitter = require("events").EventEmitter,
util = require('util');
function Foo() {
EventEmitter.call(this);
this.on('hello', function() {
console.log("World");
});
}
util.inherits(Foo, EventEmitter);
Foo.prototype.start = function() {
console.log('Hello');
this.emit('hello');
}
var foo = new Foo();
foo.start();
FYI, I tested this script on node v0.12.2 on my own computer and it produced the output:
Hello
World
Personally, I don't see how it could have worked on a previous version of node.js either because your code simply wasn't registering any event handlers. So, I can't explain that part of your question, but this code suggestion will work with both versions of node.js.