I'm trying to understand how objects bee 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.
I'm trying to understand how objects bee 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.
-
1
The more important thing is what follows that,
util.inherits(Job, EventEmitter);
. Please check this – thefourtheye Commented Sep 16, 2015 at 21:31 - blog.slaks/2013-09-03/traditional-inheritance-in-javascript – SLaks Commented Sep 16, 2015 at 21:34
4 Answers
Reset to default 3I'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 Job
s 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.
This worked for me
let events = require('events');
let eventEmitter = new events.EventEmitter();
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();
Below the Job definition you can inherit from EventEmitter as follows
util.inherits(Job, EventEmitter);
Job will bee an eventemitter as you want. Thats a good way of "extending" an "object"