关于javascript:发布订阅模式

0次阅读

共计 1106 个字符,预计需要花费 3 分钟才能阅读完成。

定义:公布 / 订阅与观察者模式原理差不多,都是定义一对多的依赖关系,当相干状态更新就会触发相应的更新
本文代码执行流程与流程图基本相同(本文仅为了加深了解,没有增加勾销订阅等办法)

     // 发布者
      function Publish() {this.themes = []
        // 增加
        this.setCol = function (theme) {this.themes.push(theme)
        }
        // 主题更新
        this.public = function (theme) {const { themes} = this
          for (let i = 0; i < themes.length; i++) {if (themes[i] === theme) {console.log(` 发布者触发 ${theme.name}主题更新 `)
              theme.notify()}
          }
        }
      }
      // 主题
      function Theme(name, callback) {
        this.name = name
        this.callback = callback
        this.subscrib = []
        this.setSub = function (sub) {this.subscrib.push(sub)
        }
        this.notify = function () {console.log(`${this.name}主题触发更新 `)
          this.subscrib.forEach((item) => {item.updated(callback)
          })
        }
      }
      // 订阅者
      function Subscrib(name) {
        this.name = name
        this.updated = function (callback) {console.log(`${this.name}接管到新音讯 `, callback(this.name))
        }
      }
      const sub1 = new Subscrib('订阅者 1')
      const sub2 = new Subscrib('订阅者 2')
      const theme1 = new Theme('三国', (e) => e)
      const theme2 = new Theme('楚汉', (e) => e)
      const publish = new Publish('发布者')
      publish.setCol(theme1)
      publish.setCol(theme2)
      theme1.setSub(sub1)
      theme2.setSub(sub1)
      theme2.setSub(sub2)
      publish.public(theme1)
      /* 
        发布者触发三国主题更新
        三国主题触发更新
        订阅者 1 接管到新音讯 订阅者 1 
      */
      publish.public(theme2)
      /* 
        发布者触发楚汉主题更新
        楚汉主题触发更新
        订阅者 1 接管到新音讯 订阅者 1
        订阅者 2 接管到新音讯 订阅者 2
       */
正文完
 0