Node.js - inheriting from EventEmitter


Question

I see this pattern in quite a few Node.js libraries:

Master.prototype.__proto__ = EventEmitter.prototype;

(source here)

Can someone please explain to me with an example, why this is such a common pattern and when it's handy?

1
83
1/17/2012 4:44:46 PM

Accepted Answer

As the comment above that code says, it will make Master inherit from EventEmitter.prototype, so you can use instances of that 'class' to emit and listen to events.

For example you could now do:

masterInstance = new Master();

masterInstance.on('an_event', function () {
  console.log('an event has happened');
});

// trigger the event
masterInstance.emit('an_event');

Update: as many users pointed out, the 'standard' way of doing that in Node would be to use 'util.inherits':

var EventEmitter = require('events').EventEmitter;
util.inherits(Master, EventEmitter);
79
7/8/2014 7:01:18 AM

ES 6 Style Class Inheritance

These come straight from the docs, but I figured it'd be nice to add them to this popular question for anyone looking.

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {
  constructor() {
    super(); //must call super for "this" to be defined.
  }
}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
  console.log('an event occurred!');
});
myEmitter.emit('event');

I'd like to git thank whoever added that. Event Emitter.

Note: The documentation does not call super() in the constructor which will cause this to be undefined. See this issue.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon