js design pattern (1) publish-subscribe model

let i = 0 
export default class Publisher {
     // all users 
    subscribers = {}

    // Subscribe events// Put all events triggered by a topic into one object 
    subscribe(topic, handler) {
         if (!(topic in  this .subscribers)) {
             this .subscribers[topic] = {}
        }

        const id = `${i++ }`
         // Number each handler and put it under the same topic 
        this .subscribers[topic][id] = handler
         return id
    }

    // logout event 
    unsubscribe(topic, id){
        const handler = this.subscribers[topic]
        delete handler[id]
    }

    // publish events 
    publish(topic, ...args) {
         // traverse all events under a topic and execute 
        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]
    }


}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324498096&siteId=291194637