EventBus 原理
通过维护类内的一个的受保护属性, 将emit
发送的事件及参数存储, 并通过on
监听事件并接收参数执行回调.
事件的存储和检索都通过 Map 来完成, Map 可以存储任何类型的键名, 非常适合检索工作.
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class EventEmitter { constructor() { this._events = new Map(); this._maxListnersNum = 10; } emit(event, ...args) { if (!this._events.get(event)) { this._events.set(event, args); } }
on(event, callback) { let payload = this._events.get(event); if (payload && payload.length > 0) { callback.apply(this, payload); } else { callback.call(this, payload); } }
off(event) { if(this._events.has(event)) { this._events.delete(event); } else { console.log('No Event'); } } }
module.exports = EventEmitter;
|
验证
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const EventEmitter = require('./eventEmitter');
const eventEmitter = new EventEmitter();
eventEmitter.emit('sayHi', {name:'Siri',text:'Hi'}); eventEmitter.on('sayHi', function({name,text}){ console.log(`${text} ${name}`); })
eventEmitter.off('sayHi') eventEmitter.on('sayHi', function(val){ console.log(val); })
|