1.发布订阅模式

  • 介绍:常被称作观察者模式,或者消息机制,定义了一种依赖关系,主要是用来解决对象之间的耦合;
  • 用例:
  • Vue实现数据的深度响应,就用到了发布订阅模式的原理,视图订阅了其依赖的数据,数据改变则会通过notify,通知视图去刷新;
  • D3.js的事件机制dispatch,也是通过利用了发布订阅模式;
  • 特点:一般在全局中定义,保证在任何地方都可以发布和订阅;

2.代码:

  • on订阅,fire发布,remove移除

    class Observer {
         constructor() {
             this.subs = []
         }
          //注册
         on(type, fn) {
             if (typeof this.subs[type] === 'undefined') {
                 this.subs[type] = [fn];
                 return;
             }
             for (let i = 0, len = this.subs[type].length; i < len; i++) {
                 if (this.subs[type][i] === fn)return;
             }
             this.subs[type].push(fn)
         }
         
         //触发
         fire(type,args){
             if (typeof this.subs[type] === 'undefined') {
                 throw "type is undefined";
                 return;
             }
             this.subs[type].forEach(sub=>{
                 sub.call(this,args)
             })
         }
         
         //移除
         remove(type,fn){
    
             if (typeof this.subs[type] === 'undefined') {
                 throw "type is undefined";
             }
             this.subs[type] = this.subs[type].filter(sub=>sub !== fn)
    
         }
     }
  • 测试

     let ob = new Observer();
      function fn1(agrs) {
          console.log("注册成功第1次");
          console.log(agrs)
      }
      function fn2(agrs) {
          console.log("注册成功第2次");
          console.log(agrs)
      }
      function fn3(agrs) {
          console.log("注册成功第3次");
          console.log(agrs)
      }
      ob.on("click", fn1);
      ob.on("click", fn2);
      ob.on("click", fn3);
      ob.on("click", fn1);
      ob.on("click", fn2);
      ob.remove("click", fn2);
      function click1() {
          ob.fire("click", "传参成功")
      }

clipboard.png


何凯
966 声望174 粉丝

Never too late to learn!