基本

事件发射器内置于 Node 中,用于 pub-sub,发布者将发出事件的模式,订阅者可以监听并做出反应。在节点术语中,发布者称为事件发射器,它们发出事件,而订阅者称为侦听器,并且它们对事件做出反应。

// Require events to start using them
const EventEmitter = require('events').EventEmitter;
// Dogs have events to publish, or emit
class Dog extends EventEmitter {};
class Food {};

let myDog = new Dog();

// When myDog is chewing, run the following function
myDog.on('chew', (item) => {
  if (item instanceof Food) {
    console.log('Good dog');
  } else {
    console.log(`Time to buy another ${item}`);
  }
});

myDog.emit('chew', 'shoe'); // Will result in console.log('Time to buy another shoe')
const bacon = new Food();
myDog.emit('chew', bacon); // Will result in console.log('Good dog')

在上面的示例中,dog 是 publisher / EventEmitter,而检查项目的函数是订阅者/侦听者。你也可以做更多的听众:

myDog.on('bark', () => {
  console.log('WHO\'S AT THE DOOR?');
  // Panic
});

单个事件也可以有多个侦听器,甚至可以删除侦听器:

myDog.on('chew', takeADeepBreathe);
myDog.on('chew', calmDown);
// Undo the previous line with the next one:
myDog.removeListener('chew', calmDown);

如果你只想听一次事件,可以使用:

myDog.once('chew', pet);

这将在没有竞争条件的情况下自动删除监听器。