2

I'm trying to understand how objects become event emitters. The documentation has something similar to the following code:

var EventEmitter = require('events').EventEmitter;

function Job(){
  EventEmitter.call(this);
}

I'm unclear what the call function is doing here, apparently calling EventEmitter's constructor?

> var j = new Job()
undefined
> j.emit('test')
TypeError: Object #<Job> has no method 'emit'

After setting the prototype via Job.prototype = new EventEmitter; seems to work as expected.

Allyl Isocyanate
  • 13,306
  • 17
  • 79
  • 130
  • 1
    The more important thing is what follows that, `util.inherits(Job, EventEmitter);`. Please check [this](https://nodejs.org/api/events.html#events_inheriting_from_eventemitter) – thefourtheye Sep 16 '15 at 21:31
  • http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ – SLaks Sep 16 '15 at 21:34

4 Answers4

3

I'm unclear what the call function is doing here, apparently calling EventEmitter's constructor?

Yes, it's basically a super call that initialises the emitter instance. See also What is the difference between these two constructor patterns? for what it does.

After setting the prototype it seems to work as expected.

Indeed, you need to let your Jobs inherit from EventEmitter. However, you really should not use new here, but rather

Job.prototype = Object.create(EventEmitter.prototype);

Also have a look at Node.js - inheriting from EventEmitter.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I think doing as in my answer is much more correct and more standard. Just my 2ct – DevAlien Sep 16 '15 at 21:44
  • @DevAlien: *Much* more correct? Not really - it's what `util.inherits` does internally. I admit that it might be the more "node" way of inheritance, while `Object.create` is just idiomatic pure JavaScript. – Bergi Sep 16 '15 at 21:48
2

This worked for me

let events = require('events');
let eventEmitter = new events.EventEmitter();
Nishan B
  • 627
  • 7
  • 11
1

With ES6 (I use babel although its not necessary for most features with the latest Node) you can just do this:

import {EventEmitter} from 'events';

export class Job extends EventEmitter {
  constructor() {
    super();
  }
}

let job = new Job();
Jason Livesay
  • 6,317
  • 3
  • 25
  • 31
  • @JasonLiveasay what is difference on import {EventEmitter} from 'events'; and from @angular/core' – Roxy'Pro May 28 '19 at 18:05
  • @Roxy'Pro They were asking about Node.js (server-side), not Angular (client-side). Also, this was four years ago -- not sure if its still the best answer related to Node.js. But you will want to try to find an answer specific to the version of Angular JS that you are using. – Jason Livesay May 30 '19 at 11:48
0

Below the Job definition you can inherit from EventEmitter as follows

util.inherits(Job, EventEmitter);

Job will become an eventemitter as you want. Thats a good way of "extending" an "object"

DevAlien
  • 2,456
  • 15
  • 17