Reputation: 169
As you can tell from this question, I'm very new to Node.js. If a question like this is not suited for this forum I do apologize and request that you direct me to a better place please.
I'm watching some training courses on Lynda and we are covering the EventEmitter. In the code below we have to add an event to the Person object. My question is, why add this event this way and not just add a function called speak to the Person object from the start? Thank you very much!
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var Person = function(name) {
this.name = name;
};
util.inherits(Person, EventEmitter);
var ben = new Person("Ben Franklin");
ben.on('speak', function(said) {
console.log(`${this.name}: ${said}`);
});
ben.emit('speak', "You may delay, but time will not.");
Upvotes: 1
Views: 40
Reputation: 9116
EventEmitter is helpful when you can't control (much) the generation of events. They can be caused by some asynchronous operation which you don't control. For example, a database disconnecting.
Here in the example, event is Ben speaking something. You don't control Ben.
You can respond to his event by defining a listener - a function which executes whenever the said event occurs.
Upvotes: 1