PJCHENder 未整理筆記

[Node] Event and EventEmitter

2020-01-31

[Node] Event and EventEmitter

Event @ Node.js Doc

1
2
3
4
5
6
7
8
9
10
// 基本使用
const EventEmitter = require('events');
const emitter = new EventEmitter();

// 註冊事件
emitter.on('foo', (event) => console.log('foo', event));

// 觸發事件,emitter.emit(eventName[, ...args])
setTimeout(() => emitter.emit('foo', {name: 'aaron'}), 1000);
// get foo, { name: 'aaron' } after 1secs
1
2
3
4
5
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.eventNames(); // 取得所有已經被註冊的事件
emitter.removeAllListeners([eventName]) // 移除所有被註冊過的事件

掃描二維條碼,分享此文章