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] } }