基本
事件發射器內建於 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);
這將在沒有競爭條件的情況下自動刪除監聽器。