发布订阅模式的写法

131 阅读2分钟
/*
发布订阅
 + 有一个对象,有人一直在看着他
 + 当这个对象发生变化的时候,第三方通知这个看着的人触发技能
 +例子  买书
    1. 普通程序怨买书 
    =》 去书店 问 没有 回家
    =》 过一会再去,问, 没有, 回家
    2.发布订阅的程序员
    =》 去书店买书, 问, 没有, 留下一个联系方式
    =》 一旦有书来, 就会接到电话
    =》 触发技能去买书
+只需要一个构造函数
 =》 创建一个第三方店员的身份
 =》 我们的任务是模拟一个 addEventListener()

 分析构造函数
 + 属性: 消息队列
 + 方法: 能向消息队列中添加内容
 + 方法: 能删除消息队列中的内容
 + 方法: 能触发消息队列中的内容
*/

class Observe{
    constructor() {
        this.message = {}
    }
    // 向消息队列添加内容
    on (type,fn) {
        // type 看的行为
        // fn 在发生该行为的时候做的事情

        // 判断该行为是否注册过来
        // 如果没有 给赋值一个一个这个行为,值赋值为 【】
        // 如果有, 直接向数组添加
        if (!this.message[type]) {
            this.message[type] = [fn]
        }else{
            this.message[type].push(fn)
        }
         
    }
    // 删除消息队列中的内容
    off (type,fn) {
        // 判断有没有函数
        if (!fn) {
            delete this.message[type]
            return 
        }
        if (!this.message[type]) return
        this.message[type] = this.message[type].filter(hand => {return hand!==fn})

    }
    // 触发消息队列内容
    trigger(type) {
        if (!this.message[type]) return
        this.message[type].forEach(fn => {
            fn()
        })
    }
}

// 使用构造函数创建一个实例
const person1 = new Observe()

// 当你向拜托这个 person1 帮你观察一些内容的时候
// 告诉你一个行为, 当行为出现的时候, 告诉你干什么

person1.on('abc',handler1)
person1.on('abc',handler2)
person1.on('hh',handler3)

// 告诉person1 这个事情你不用管来
// 1.只告诉你这个事情你不用管了 
// 2. 把这个事情下面的处理函数去掉

person1.off('abc',handler1)

person1.trigger('hh')

function handler1 () {console.log(1)}
function handler2 () {console.log(2)}
function handler3 () {console.log(3)}

console.log(person1)