如何对eventEmitter进行子类划分?我正在尝试以下测试:
var util = require('util')
,events = require('events');
function Downloader() {
events.EventEmitter.call(this);
}
util.inherits(Downloader, events.EventEmitter);
console.log(new Downloader() instanceof events.EventEmitter); // true
Downloader.prototype.download = function(episode) {
var self = this;
var statusMessage = 'Downloading: ' + episode;
self.emit('status', statusMessage);
setTimeout(function() {
var finishedMessage = 'Downloaded ' + episode;
self.emit('finished', finishedMessage);
}, 5000);
}
exports.Downloader = new Downloader();
节点抱怨“object”没有“on”方法。但是,当检查eventemitter的下载实例时返回true。
有人能解释吗?谢谢!
最佳答案
哦,天哪。首先应该是“module.exports”。其次,它的“instanceof”不是“instanceof”。
我的错。这是一个有效的例子
var util = require('util')
,events = require('events');
function Downloader() {
events.EventEmitter.call(this);
}
util.inherits(Downloader, events.EventEmitter);
Downloader.prototype.download = function(episode) {
var self = this;
var statusMessage = 'Downloading: ' + episode;
self.emit('status', statusMessage);
setTimeout(function() {
var finishedMessage = 'Downloaded ' + episode;
self.emit('finished', finishedMessage);
}, 5000);
}
module.exports = new Downloader();
关于javascript - 子类化event.EventEmitter不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16784853/