1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- /**
- * @description 发布订阅对象
- * 一个简单的发布者、订阅者模式,提供了发布、订阅、删除的方法
- * from chinyan
- */
- class PubsubService {
- private topics: Record<string, ((params?: any) => void)[]> = {}
- // 发布事件
- publish(topic: string, data: any) {
- if (!this.topics[topic]) return
- this.topics[topic].forEach((fn) => fn(data))
- }
- // 订阅事件
- subscribe(topic: string, callback: (params?: any) => void) {
- if (!this.topics[topic]) {
- this.topics[topic] = []
- }
- if (!this.topics[topic].includes(callback)) {
- this.topics[topic].push(callback)
- }
- // 返回取消订阅的方法
- return () => {
- const index = this.topics[topic].indexOf(callback)
- if (index !== -1) {
- this.topics[topic].splice(index, 1)
- }
- }
- }
- // 清空所有订阅者
- clearAllSub() {
- this.topics = {}
- }
- // 清空某个主题的订阅者
- clearSubsByTopic(topic: string) {
- if (this.topics[topic]) {
- this.topics[topic] = []
- }
- }
- // 判断是否有某个主题的订阅者
- hasSubsByTopic(topic: string) {
- return this.topics[topic] && this.topics[topic].length > 0
- }
- }
- // 实例化并导出单例
- export default new PubsubService()
|