0

See example below. I am trying to trigger an event on a.

var events = require("events");

function foo() {
    this.on("ping", function() {
        console.log("bar!");
    })
}

foo.prototype = new events.EventEmitter();
var a = new foo();
var b = new foo();
a.emit("ping");

This prints "bar!" two times, so I am assuming I am adding the event listener on "all" the functions, not the specific instance. Since I am running foo two times, I am adding two event listeners, nothing strange really, althought not so intuitive.

Is there a way to add the event listener only on a?

(Please edit this question if I am using the wrong terminology, used to class-based programming)

edit: So I suspect it is because I am using the same event emitter as prototype.. But in that case, how can I create one for each new foo()?

Marcus Johansson
  • 2,626
  • 2
  • 24
  • 44
  • Maybe this [article on the EventEmitter](http://blog.ashworth.in/how-to-use-the-node-js-eventemitter/) will help you? – Brendan Oct 18 '14 at 22:08

1 Answers1

1

Typically you inherit (from EventEmitter) like this:

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

function Foo() {
  if (!(this instanceof Foo))
    return new Foo();

  EventEmitter.call(this);

  this.on('ping', function() {
    console.log('bar!');
  });
}
inherits(Foo, EventEmitter);

// add Foo-specific prototype functions *after* `inherits()`
Foo.prototype.myfunc = function(a, b) {
  return a + b;
});

var a = new Foo();
var b = new Foo();
a.emit('ping');

This is the setup that most modules on npm and objects in node core use to inherit from another object.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Rather than just a block of code with no description, can you describe what is operationally different between your code and the OP's code? The OP is setting the prototype to be an EventEmitter. – jfriend00 Oct 18 '14 at 21:34
  • The OP already pointed out the main problem with their code: `So I suspect it is because I am using the same event emitter as prototype.. But in that case, how can I create one for each new foo()` – mscdex Oct 18 '14 at 23:20