Node.js EventEmitter事件不再在节点12.1+上触发

我已经将问题解决回到以下代码:

var EventEmitter = require("events").EventEmitter, util = require('util'); function Foo() { EventEmitter.call(this); } util.inherits(Foo, EventEmitter); Foo.prototype.on('hello', function() { console.log("World"); }); Foo.prototype.start = function() { console.log('Hello'); this.emit('hello'); } var foo = new Foo(); foo.start(); 

使用Node v0.10.36这个代码输出:

你好,世界

但是使用Node v0.12.1的代码输出:

你好

看起来监听器在Node的更高版本中不再起作用。

这是模块的一部分,是导出/需要的,所以我试图让听众远离模块的一个实例。

任何人都可以解释为什么这停止工作,以及build议如何做到这一点。

你不能把一个.on()处理程序放在你的原型上。 你的对象的EventEmitter部分甚至不知道它在那里,没有事件处理程序已经注册到EventEmitter基础对象。

相反,您需要在实例化对象之后安装事件处理程序,以便EventEmitter有机会实际注册事件处理程序。

 var EventEmitter = require("events").EventEmitter, util = require('util'); function Foo() { EventEmitter.call(this); this.on('hello', function() { console.log("World"); }); } util.inherits(Foo, EventEmitter); Foo.prototype.start = function() { console.log('Hello'); this.emit('hello'); } var foo = new Foo(); foo.start(); 

仅供参考,我在我自己的计算机上testing了节点v0.12.2上的这个脚本,它产生了输出:

 Hello World 

就个人而言,我不明白它是如何工作在以前的版本的node.js,因为你的代码只是没有注册任何事件处理程序。 所以,我不能解释你的问题的一部分,但是这个代码build议将适用于两个版本的node.js。