关于前端:发布订阅学习

5次阅读

共计 495 个字符,预计需要花费 2 分钟才能阅读完成。

公布订阅模式学习

公布订阅模式优缺点

  • 用于跨组件通信
  • 用于一对多,一处公布,多出订阅
  • 不好保护
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)
                }
            }
        }
    }
正文完
 0