js设计模式(一)发布订阅模式

let i = 0
export default class Publisher {
    // 所有用户
    subscribers = {}

    // 订阅事件 // 将一个topic触发的所有事件放到一个对象中
    subscribe(topic, handler) {
        if (!(topic in this.subscribers)) {
            this.subscribers[topic] = {}
        }

        const id = `${i++}`
        // 给每个handler编号,然后放到同一个topic下
        this.subscribers[topic][id] = handler
        return id
    }

    // 注销事件
    unsubscribe(topic, id){
        const handler = this.subscribers[topic]
        delete handler[id]
    }

    // 发布事件
    publish(topic, ...args) {
        // 遍历一个topic下的所有事件,并执行
        for (const key in this.subscribers[topic]) {
            const handler = this.subscribers[topic][key]
            if (typeof handler === 'function') {
                handler(...args)
            }
        }
    }

    // 清除topic
    clear(topic) {
        delete this.subscribers[topic]
    }


}

猜你喜欢

转载自www.cnblogs.com/zhoulixue/p/8862827.html