0

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?

Grayda
  • 1,870
  • 2
  • 25
  • 43

1 Answers1

2

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();
DevAlien
  • 2,456
  • 15
  • 17
  • I also worked this out the very second you posted the comment. I could have sworn that I did this earlier when preparing to post the question, but obviously not / I might have had other issues getting in the way. My code now works correctly. Thank you! – Grayda Sep 14 '15 at 07:48