2013-01-03 51 views
0

我當試圖繼承EvenEmitterNode.js的EventEmitter錯誤

/* Consumer.js */ 
var EventEmitter = require('events').EventEmitter; 
var util = require('util'); 

var Consumer = function() {}; 

Consumer.prototype = { 
    // ... functions ... 
    findById: function(id) { 
    this.emit('done', this); 
    } 
}; 

util.inherits(Consumer, EventEmitter); 
module.exports = Consumer; 

/* index.js */ 
var consumer = new Consumer(); 
consumer.on('done', function(result) { 
    console.log(result); 
}).findById("50ac3d1281abba5454000001"); 

/* ERROR CODE */ 
{"code":"InternalError","message":"Object [object Object] has no method 'findById'"} 

我已經試過幾乎所有的東西,仍然不工作

回答

3

幾件事情有一個錯誤。您正在覆蓋原型而不是擴展原型。另外,在添加新方法之前移動util.inherits()調用:

var EventEmitter = require('events').EventEmitter; 
var util = require('util'); 

var Consumer = function Consumer() {} 

util.inherits(Consumer, EventEmitter); 

Consumer.prototype.findById = function(id) { 
    this.emit('done', this); 
    console.log('found'); 
}; 

var c = new Consumer(); 
c.on('done', function(result) { 
    console.log(result); 
}); 

c.findById("50ac3d1281abba5454000001"); 
+0

我只是注意到了繼承問題,爲什麼要離開c.findById appart? – jtomasrl

+0

只是爲了便於閱讀,它試圖確保我瞭解您的代碼。 –

+0

也,爲什麼Consumer.prototype = {}不會工作,但Consumer.prototype.function是 – jtomasrl