发布订阅模式实现

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值