发布订阅模式学习
发布订阅模式优缺点
- 用于跨组件通信
- 用于一对多,一处发布,多出订阅
- 不好维护
class Pubsub {
list = {};//用于装订阅函数
listen(key, fn) {
//如果list对象中没有数组装fns给以数组用于装fns
if (!this.list[key]) {
this.list[key] = []
}
this.list[key].push(fn)
}
//发布
publish(key, ...args) {
if (!this.list[key] || this.list[key].length == 0) return;
for (let i = 0; i < this.list[key].length; i++) {
const fn = this.list[key][i];
fn.apply(this, args)
}
}
//移除
remove(key, fn) {
const fns = this.list[key];
if (!fns || fns.length == 0) return false;
for (let i = 0; i < fns.length; i++) {
const _fn = fns[i]
if (_fn == fn) {
fns.splice(i, 1)
}
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。