zoukankan      html  css  js  c++  java
  • 手写一个发布订阅

        1:所有的发布订阅就是一个对象。
        class Obersve {
          event={}  //等价于下面的constructor
          // constructor() {
          //   this.event = {}
          // }
          subscribe(type, fn) { //订阅
            if (Object.keys(this.event).includes(type)) { 
              this.event[type].push(fn)
            } else {
              this.event[type] = [fn]
            }
          }
          publish(type, args = {}) {  //发布
            if (this.event[type]) {
              this.event[type].map(item => {
                item.call(this, { type,args}) 
              })
            }
          }
        }
        const ober = new Obersve()
        ober.subscribe('aaa', function (e) {
          console.log(`事件: ${e.type}`)
          console.log(`消息: ${e.args.message}`)
        })
        ober.publish('aaa', {
          message: '亮哥'
        })
  • 相关阅读:
    day04
    day02
    day01
    if语句用户交互字符串
    python安装和pycharm安装教程
    day1预习
    博客园的使用
    python day 3
    从cbv到fbv:用函数写视图与用类写视图的区别(drf与restful)
    resful规范: 进行数据交换时的代码潜规则
  • 原文地址:https://www.cnblogs.com/binglove/p/13305054.html
Copyright © 2011-2022 走看看