Vue发布订阅模式

# 发布订阅模式

  • 发布订阅模式是一种消息范式,消息的发送者(发布者)不会直接将消息发送给接收者(订阅者),而是通过一个第三方组件(通常称为事件总线或消息代理)来传递消息。

  • 发布订阅模式的主要优点是解耦了消息的发送者和接收者,使得它们可以独立地变化和扩展。发布订阅模式广泛应用于事件驱动编程、异步编程和消息队列等领域。

# Vue 事件中心实现

  • eventEmitter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const eventName = ['EVENT_NAME', 'EVENT_NAME1', 'EVENT_NAME2', ...] // 

class EventEmitter {
private listeners:Record<string, Set<Function>> = {
'EVENT_NAME':new Set(),
'EVENT_NAME1':new Set(),
'EVENT_NAME2':new Set(),
...
} // 定义事件监听器

on(eventName: string, listener: Function) {
this.listeners[eventName].add(listener)
}

emit(eventName: string, ...args: any[]) {
this.listeners[eventName].forEach((listener) => listener(...args))
}
}

export default new EventEmitter()
  • 事件发送
1
2
import emitter from './eventEmitter'
emitter.emit('EVENT_NAME')
  • 事件监听处理
1
2
import emitter from './eventEmitter'
emitter.on("EVENT_NAME", function() {...})

# 代码优化

事件优先级、事件中断