1

I'm trying to understand the EventEmitter module in Node.js. Reading the apidoc at nodejs.org tells me this:

Functions can then be attached to objects, to be executed when an event is emitted. These functions are called listeners. Inside a listener function, this refers to the EventEmitter that the listener was attached to.

The thing is, when I play around a little with this I find that it, in my understanding, doesn't follow the doc.

var events = require('events');

function Person(nameInput){
    this.name = nameInput;
    this.sayMyName = function(preString){
        console.log(preString + this.name);
    }
}

Person.prototype = new events.EventEmitter();

var person1 = new Person("James");
var person2 = new Person("Daniel");

person1.addListener('sayit', function(){
    this.sayMyName("Hello ");
});

person2.addListener('sayit', function(){
    this.sayMyName("Hi ");
});

person1.emit('sayit');

//console prints out:
Hello James
Hi James

My question is. Given the docs saying this refers to the EventEmitter that the listener was attached to (person1 resp. person2 in my case), shouldn't the output of the program be like this?

Hello James
Hi Daniel

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Gustav
  • 1,361
  • 1
  • 12
  • 24

1 Answers1

1

That's the problem when you have initialised only (exactly) one EventEmitter for all your Person instances:

Person.prototype = new events.EventEmitter();

That will create only one listener store which is shared amongst all instances - just as prototypes should work. See also What is the reason to use the 'new' keyword at Derived.prototype = new Base.

To make the inheritance correct, you need to do

function Person(nameInput){
    events.EventEmitter.call(this);
    this.name = nameInput;
}

Person.prototype = Object.create(events.EventEmitter.prototype);

This does not create an EventEmitter for the prototype, but only inherits from it. Every Person instance will then initialise its own emitter (even if that would be done by addListener or emit automatically, it's still a good thing to do).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375