Node.js EventEmitter – 不好的事情正在发生

我一直在试图解决一个nodejs应用程序中的错误,并缩小到我已经实现事件发射器的方式。 该应用程序是一个express.js应用程序,使用类。 NodeJS的一些关键方面,我必须缺less,围绕内存使用和类/对象生命周期。 我希望有人能指出我为什么没有按预期工作。

代码如下:

// ServiceWrapper.js: var events = require('events'); var ServiceClient = function(opts) { this.foobar = ""; this.opts = opts; this.hasFoo = false, this.hasBar = false; } ServiceClient.prototype = new events.EventEmitter(); ServiceClient.prototype.getFoo = function() { var self = this; self.hasFoo = true; self.foobar += "foo"; self.emit('done','foo'); } ServiceClient.prototype.getBar = function() { var self = this; self.hasBar = true; self.foobar += "bar"; self.emit('done','bar'); } var ServiceWrapper = function(){} ServiceWrapper.prototype.getResponse = function(options, callback) { var servClient = new ServiceClient({}); servClient.on('done', function(what) { if (servClient.hasFoo && servClient.hasBar) { console.log("foo && bar") callback(servClient.foobar); } else { console.log("Don't have everything: " + servClient.foobar); } }); servClient.getFoo(); servClient.getBar(); } module.exports = ServiceWrapper 

然后在我的快速应用程序:

 var ServiceWrapper = require('ServiceWrapper'); app.get('/serviceReponse', function(req,res) { var servWrapper = new ServiceWrapper(); servWrapper.getResponse(function(ret) { res.end(ret); }); }); 

Web应用程序的行为按预期工作:响应设置为“foobar”。 但是,查看日志,看起来像是内存泄漏 – 多个servWrapper实例。 启动应用程序后,第一个请求会生成:

 Don't have everything: foo foo && bar 

但是,如果我刷新页面,我看到这个:

 foo && bar Don't have everything: foo foo && bar foo && bar 

随着每次刷新,侦听器都会检测到多个“已完成”事件 – foo && bar输出不断增长(假设存在越来越多的ServiceWrapper实例)。

为什么会发生? (我希望看到从每个请求的第一个请求我得到的输出)。

感谢freenode上#node.js上的人帮助:

当然,但是每次你附加监听器,你都将它们附加到同一个发射器上,因为你没有将原型的状态本地化到你的实例中,原型方法就会根据原型对象的状态来进行操作。 我相信你可以通过在构造函数中完成EventEmitter.call(this)来修复它

请参阅以下链接了解更多信息: