观察者模式

  • 观察者模式指的是函数自动观察数据对象,一旦对象有变化,函数就会自动执行。而 js 中最常见的观察者模式就是事件触发机制
    class eventObs {
      // 要有一个对象,存储着它自己的触发函数。而且这个对象的触发函数可能有很多种
      // 那么 handler 的属性应该是一个数组,每个数组的值都是一个函数。type1:[func1,func2...]
      constructor() {
        this.handleFunc = {};
      }

      // 添加事件监听
      add(type, func) {
        if (this.handleFunc[type]) {
          // 当存在type时,判断是否存在当前触发函数
          if (this.handleFunc[type].indexOf(func) === -1) {
            this.handleFunc[type].push(func);
          }
        } else {
          // 当不存在当前类型
          this.handleFunc[type] = [func];
        }
      }

      // 触发事件监听
      fire(type, func) {
        try {
          if (arguments.length === 1) {
            // 没有输入触发函数,默认触发所有函数
            let target = this.handleFunc[type];
            let length = target.length;
            for (let i = 0; i < length; i++) {
              target[i]();
            }
          } else {
            // 当输入func参数代表只触发func函数
            let target = this.handleFunc[type];
            let index = target.indexOf(func);
            // 当不存在该触发函数时报错
            if (index === -1) {
              throw error;
            }
            func();
          }
          return true;
        } catch (e) {
          console.error("请触发存在的函数!");
          return false;
        }
      }

      // 移除事件监听
      remove(type, func) {
        try {
          let target = this.handleFunc[type];
          let index = target.indexOf(func);
          if (index === -1) {
            throw error;
          }
          target.splice(index, 1);
        } catch (e) {
          console.error("请删除存在的函数!");
        }
      }

      // 触发事件监听后移除
      once(type, func) {
        this.fire(type, func) ? this.remove(type, func) : null;
      }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值