已经有很多问题了,如何从nodejs的构造函数中发出事件。大多数此类问题 - 在添加监听器之前触发事件:
var fooBar = new FooBar() // event is emitted
fooBar.on('event', function(){}); // never will be executed
有一个解决方法:仅在 newListener
event is fired 之后才在构造函数中触发事件。在这种情况下,只能添加一个监听器。这是正常做法吗?
我发现 readline 实际上提供了相同的接口(interface):
var io = readline.createInterface({
input: process.stdin,
terminal: false
});
io.on('line', function(line) {}); // listener is added after constructor
它可以使用 newListener
事件吗?
最佳答案
这是另一种解决方法,使用 setImmediate
:
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
function FooBar() {
var instance = this;
EventEmitter.call(instance);
setImmediate(function() {
instance.emit('event', 'hello world');
});
}
inherits(FooBar, EventEmitter);
var fooBar = new FooBar();
fooBar.on('event', function(value) {
console.log('got event:', value);
});
这使得事件异步发出,这意味着它将被安排到任何同步代码(例如调用构造函数和添加事件监听器)运行之后。
关于node.js - 如何从nodejs中的构造函数发出/捕获事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32089494/