0

I'm having some trouble with a custom event emitter in Nodejs. I'm pretty sure I've created the eventemitter correctly, since I can fire and catch events on its instances.

However, none of the events in its constructor are being fired. They all seem to exist and are registering their listeners correctly, but the this.emit function doesn't do anything.

For clarity, here's a minimum failing example:

var EventEmitter = require("events").EventEmitter,
    util = require("util");

var MyEmitter = function() {
    var self = this;
    EventEmitter.call(this);

    someExternalFunction(function callback() {
        self.emit("event 1"); // Does not fire
        console.log("fires");
    });   

    this.emit("event 2"); // Does not fire

    return this;
};

util.inherits(Browser,EventEmitter);

var myEmitterInstance = new MyEmitter();

myEmitterInstance.emit("event 3");  // fires

myEmitterInstance.on("event 1 - does not fire", function () {

//Do something with the results of someExternalFunction.

} // this function never runs.

I can't understand what I've done wrong.

Racheet
  • 730
  • 8
  • 21
  • 2
    Where are you actually attaching these event handlers? Your problem is probably that you are firing the event before the code adds listeners. – loganfsmyth Jun 05 '14 at 16:28
  • 2
    I thing @loganfsmyth is right. How could you register a listener for an event emitter before it is constructed? And so, what is the point of emitting an event in a constructor if nobody has had a chance to subscribe to it? – Edwin Dalorzo Jun 05 '14 at 16:32
  • I added some code to show how I'm listening for the events. "someExternalFunction" is actually spinning up a phantomjs instance, and the event is triggered in it's callback. With logging statements, I've seen that code written below the listener fires before phantomjs finishes spinning up. – Racheet Jun 05 '14 at 17:21
  • on the other hand, you've both made valuable points I really should have considered beforehand. – Racheet Jun 05 '14 at 17:21
  • @loganfsmyth Thanks, that comment helped me find a code permutation that worked. I'd happily accept if you wrote it as an answer. – Racheet Jun 06 '14 at 10:07

0 Answers0