JS设计模式之发布订阅模式

JS设计模式之发布订阅模式

class Observe {
            constructor() {
                this.cacheList = {}
            }
            publish(type, message) {
                this.cacheList[type] && this.cacheList[type].forEach(item => item(message))
            }
            subscribe(type, call) {
                this.cacheList[type] ? (this.cacheList[type].push(call)) : (this.cacheList[type] = [call])
            }
            unSubscribe(type, call) {
                type || (this.cacheList = {});
                if (type && !call) {
                    delete this.cacheList[type]
                } else {
                    this.cacheList[type] && (this.cacheList[type] = this.cacheList[type].filter(item => item !==
                        call))
                }
            }
        }
class DefineLoclStorage {
        static getItem(key = "") {
          let data = localStorage.getItem(key);
          try {
            data = JSON.parse(data);
          } catch (error) {
            throw error;
          }
          return data;
        }

        static getItemPubsub(key, cb) {
          if (!Array.isArray(this.EventList[key])) {
            this.EventList[key] = [];
          }
          const ID = ++this.EventId;
          this.EventList[key].push({
            id: ID,
            cb,
          });
          return ID;
        }

        static clearItemEvent(key, id) {
          if (!Array.isArray(this.EventList[key])) {
            this.EventList[key] = [];
          }
          this.EventList[key] = this.EventList[key].filter(
            (item) => item.id !== id
          );
        }
        static dispatch(key, value) {
          const data = value || this.getItem(key);
          const event = this.EventList[key] || [];
          event.forEach((item) => {
            if (typeof item?.cb == "function") {
              item?.cb(data);
            }
          });
        }
        static setItem(key, data) {
          localStorage.setItem(key, JSON.stringify(data));
          this.dispatch(key, data);
        }

        static pushItem(key, value) {
          const data = this.getItem(key) || [];
          data.push(value);
          this.setItem(key, data);
        }
        static setArraryItem(key,cb){
            if(typeof cb !=="function"){
             throw new Error('cb must be a gunction')
             return 
            }
            this.setItem(key,cb(this.getItem(key)))
        }
        static EventList = {};
        static EventId = 0;
      }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值