admin管理员组文章数量:1356515
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"
本文标签: javascriptEvent emitter constructorStack Overflow
版权声明:本文标题:javascript - Event emitter constructor - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744050079a2582260.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论