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()?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.