说说nodejs中的EventEmit是如何实现的
# 是什么
EventEmitter:是nodejs实现事件驱动的基础, 可以理解成发布订阅模式
- 几乎所有模块都继承了这个类
- 可以监听/绑定监听器, 实现了异步操作
# 怎么用
实现一个EventEmitter类
class EventEmitter {
constructor() {
this.events = {};
}
on(type, handler) {
if (!this.events[type]) {
this.events[type] = [];
}
this.events[type].push(handler);
}
off(type, handler) {
if (!this.events[type]) return;
this.events[type] = this.events[type].filter((item) => item !== handler);
}
emit(type) {
const args = [...arguments].slice(1)
this.events[type].map(handler =>{
handler(args)
})
}
once(type,handler) {
const fn = (...args) =>{
handler.apply(this, args)
this.off(type, fn)
}
this.on(type, fn)
}
}
const emitter = new EventEmitter()
emitter.on('d1', ()=>{
console.log('打老虎')
})
emitter.on('d1', ()=>{
console.log('打狮子')
})
emitter.once('d1', ()=>{
console.log('打豹子')
})
emitter.emit('d1')
// 打老虎
// 打狮子
// 打豹子
emitter.emit('d1')
// 打老虎
// 打狮子
// 少了一个打豹子
# 原理
# FAQ
上次更新: 2021/12/19, 18:05:42