I'm trying to write a simple library in node.js. Here's my library code, in a file called "index.js" in the "lib" folder:
var util = require("util");
var EventEmitter = require("events").EventEmitter;
util.inherits(Foo, EventEmitter);
function Foo() {
EventEmitter.call(this);
}
Foo.prototype.Something = function() {
console.log("Hello World")
this.emit("ready")
}
module.exports = Foo
And here's some test code in a file called index.js in the root of my project folder:
var Foo = require("./lib/index.js");
var foo = new Foo();
foo.Something();
foo.on("ready", function() {
console.log("Blah")
})
When I run this code with node v0.12.7
, I see "Hello World", but not "Blah"
I don't think I'm doing anything wrong, as I've used emitters before in another project, but even copying that code doesn't work.
Any clues as to why it's not working?
The only thing you are doing wrong is that you call the function (emit the event) before you listen to it.
Just invert the last 2 statements
foo.on("ready", function() {
console.log("Blah");
});
foo.Something();