Search code examples
node.jseventemitter

Node: extend EventEmitter to non-prototype object


I see this all the time:

Parrot.prototype.__proto__ = EventEmitter.prototype;

With this, each time you construct a new parrot, it can squawk.

However, supposing I construct an object with functions and don't intend to create multiple instances:

var parrot = {
  squawk: function(whatYouSaid){
    this.emit("SQUAWK!!!!", whatYouSaid);
  }
}

How would I make this extend EventEmitter? I tried this, and it didn't work:

_.extend(parrot, (new EventEmitter()));

Solution

  • You should extend/assign EventEmitter.prototype to your object:

    _.assign(parrot, EventEmitter.prototype);