'newListener' 事件


在将监听器添加到其内部监听器数组之前,EventEmitter 实例将触发自身的 'newListener' 事件。

'newListener' 事件注册的监听器会传入事件名称和对正在添加的监听器的引用。

在添加监听器之前触发事件这一事实有一个微妙但重要的副作用:在 'newListener' 回调中注册到同一个 name 的任何其他监听器都会在正在添加的监听器之前插入。

class MyEmitter extends EventEmitter {}

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

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 are 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 are inserted before the listener that is in the process of being added.

class MyEmitter extends EventEmitter {}

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