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

5 篇文章 1 订阅

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;
      }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
发布订阅模式又称观察者模式,是一种常见的设计模式,它定义了对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。下面是手写JavaScript发布订阅模式的一种实现方式: ```javascript function PubSub() { this.subscribers = {}; } PubSub.prototype.subscribe = function(event, callback) { if (!this.subscribers[event]) { this.subscribers[event] = []; } this.subscribers[event].push(callback); }; PubSub.prototype.unsubscribe = function(event, callback) { if (!this.subscribers[event]) { return; } var index = this.subscribers[event].indexOf(callback); if (index > -1) { this.subscribers[event].splice(index, 1); } }; PubSub.prototype.publish = function(event, data) { if (!this.subscribers[event]) { return; } this.subscribers[event].forEach(function(callback) { callback(data); }); }; ``` 使用方式如下: ```javascript var pubsub = new PubSub(); function callback1(data) { console.log('callback1:', data); } pubsub.subscribe('event1', callback1); function callback2(data) { console.log('callback2:', data); } pubsub.subscribe('event2', callback2); pubsub.publish('event1', { message: 'hello' }); pubsub.publish('event2', { message: 'world' }); pubsub.unsubscribe('event1', callback1); pubsub.publish('event1', { message: 'hello again' }); ``` 输出结果为: ``` callback1: {message: "hello"} callback2: {message: "world"} ``` 当调用 `publish` 方法时,订阅了该事件的所有回调函数都将被执行,并且可以传递一个数据对象作为参数。调用 `subscribe` 方法注册一个回调函数,当该事件被发布时,该回调函数将被执行。调用 `unsubscribe` 方法取消订阅

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值