如何将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();
节点抱怨'对象'没有方法'打开'。但是当检查Downloader instanceOf EventEmitter时返回true。
有人可以解释一下吗?谢谢!
答案 0 :(得分:3)
哦,天哪。首先它应该是'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();