130 字
1 分钟
手写发布订阅
// 发布订阅
class EventEmitter {
constructor() {
this.cache = {}
}
// 订阅事件
on(name, callback, once = false) {
if (!this.cache[name]) {
this.cache[name] = []
}
this.cache[name].push({
callback,
once
})
}
// 只订阅一次
once(name, callback) {
this.on(name, callback, true)
}
// 发布
emit(name, ...rest) {
if (!this.cache[name]) {
return
}
this.cache[name].forEach((param, index) => {
const { once, callback } = param;
if (once) {
this.cache[name].splice(index, 1);
if (!this.cache[name]?.length) delete this.cache[name]
}
callback.call(this, ...rest)
})
}
// 取消订阅
off(name, callback) {
if (!name) { this.cache = {}; return; }
if (!callback) { delete this.cache[name]; return }
if (!this.cache[name]) { return }
const i = this.cache[name].findIndex((f) => f.callback === callback)
this.cache[name].splice(i, 1);
if (!this.cache[name].length) delete this.cache[name]
}
}
手写发布订阅
https://nollieleo.github.io/posts/手写发布订阅/
作者
翁先森
发布于
2021-12-13
许可协议
CC BY-NC-SA 4.0