'newListener' 事件
eventName
<string> | <symbol> 正在监听的事件的名称listener
<Function> 事件处理函数
在将监听器添加到其内部监听器数组之前,EventEmitter
实例将触发自身的 'newListener'
事件。
const myEmitter = new MyEmitter();
// 只做一次,这样就不会永远循环
myEmitter.once('newListener', (event, listener) => {
if (event === 'event') {
// 在前面插入新的监听器
myEmitter.on('event', () => {
console.log('B');
});
}
});
myEmitter.on('event', () => {
console.log('A');
});
myEmitter.emit('event');
// 打印:
// B
// A
eventName
<string> | <symbol> The name of the event being listened forlistener
<Function> The event handler function
The EventEmitter
instance will emit its own 'newListener'
event before
a listener is added to its internal array of listeners.
Listeners registered for the 'newListener'
event will be passed the event
name and a reference to the listener being added.
The fact that the event is triggered before adding the listener has a subtle
but important side effect: any additional listeners registered to the same
name
within the 'newListener'
callback will be inserted before the
listener that is in the process of being added.
const myEmitter = new MyEmitter();
// Only do this once so we don't loop forever
myEmitter.once('newListener', (event, listener) => {
if (event === 'event') {
// Insert a new listener in front
myEmitter.on('event', () => {
console.log('B');
});
}
});
myEmitter.on('event', () => {
console.log('A');
});
myEmitter.emit('event');
// Prints:
// B
// A