There are already a lot of questions, how to emit event from constructor in nodejs. Most number of this issues - event is fired before listener is added:
已经有很多问题,如何从nodejs中的构造函数发出事件。大多数问题 - 在添加侦听器之前触发事件:
var fooBar = new FooBar() // event is emitted
fooBar.on('event', function(){}); // never will be executed
There is a workaround: to fire event in constructor only after newListener
event is fired. In this case, only one listener can be added. Is this normal practice to do that?
有一种解决方法:仅在触发newListener事件后才在构造函数中触发事件。在这种情况下,只能添加一个侦听器。这是正常做法吗?
I see that readline in fact provides same interface:
我看到readline实际上提供了相同的接口:
var io = readline.createInterface({
input: process.stdin,
terminal: false
});
io.on('line', function(line) {}); // listener is added after constructor
Does it work using newListener
event?
它是否可以使用newListener事件?
1 个解决方案
#1
3
Here's another workaround, using setImmediate
:
这是使用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);
});
This makes emitting the event asynchronous, which means that it will be scheduled until after any synchronous code (like calling the constructor and adding the event listener) is run.
这使得事件发生异步,这意味着它将被调度,直到运行任何同步代码(如调用构造函数和添加事件侦听器)之后。
#1
3
Here's another workaround, using setImmediate
:
这是使用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);
});
This makes emitting the event asynchronous, which means that it will be scheduled until after any synchronous code (like calling the constructor and adding the event listener) is run.
这使得事件发生异步,这意味着它将被调度,直到运行任何同步代码(如调用构造函数和添加事件侦听器)之后。