2

如何继承 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'方法。但是,当检查 Downloader instanceOf EventEmitter 时返回 true。

有人可以解释吗?谢谢!

4

1 回答 1

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();
于 2013-05-28T06:04:09.823 回答