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