Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - inheriting from EventEmitter

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?

like image 457
jeffreyveon Avatar asked Jan 17 '12 16:01

jeffreyveon


2 Answers

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); 

2nd Update: with ES6 classes upon us, it is recommended to extend the EventEmitter class now:

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

See https://nodejs.org/api/events.html#events_events

like image 121
alessioalex Avatar answered Oct 01 '22 09:10

alessioalex


ES6 Style Class Inheritance

The Node docs now recommend using class inheritence to make your own event emitter:

const EventEmitter = require('events');  class MyEmitter extends EventEmitter {   // Add any custom methods here }  const myEmitter = new MyEmitter(); myEmitter.on('event', () => {   console.log('an event occurred!'); }); myEmitter.emit('event'); 

Note: If you define a constructor() function in MyEmitter, you should call super() from it to ensure the parent class's constructor is called too, unless you have a good reason not to.

like image 33
Breedly Avatar answered Oct 01 '22 09:10

Breedly