PubsubService.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * @description 发布订阅对象
  3. * 一个简单的发布者、订阅者模式,提供了发布、订阅、删除的方法
  4. * from chinyan
  5. */
  6. class PubsubService {
  7. private topics: Record<string, ((params?: any) => void)[]> = {}
  8. // 发布事件
  9. publish(topic: string, data: any) {
  10. if (!this.topics[topic]) return
  11. this.topics[topic].forEach((fn) => fn(data))
  12. }
  13. // 订阅事件
  14. subscribe(topic: string, callback: (params?: any) => void) {
  15. if (!this.topics[topic]) {
  16. this.topics[topic] = []
  17. }
  18. if (!this.topics[topic].includes(callback)) {
  19. this.topics[topic].push(callback)
  20. }
  21. // 返回取消订阅的方法
  22. return () => {
  23. const index = this.topics[topic].indexOf(callback)
  24. if (index !== -1) {
  25. this.topics[topic].splice(index, 1)
  26. }
  27. }
  28. }
  29. // 清空所有订阅者
  30. clearAllSub() {
  31. this.topics = {}
  32. }
  33. // 清空某个主题的订阅者
  34. clearSubsByTopic(topic: string) {
  35. if (this.topics[topic]) {
  36. this.topics[topic] = []
  37. }
  38. }
  39. // 判断是否有某个主题的订阅者
  40. hasSubsByTopic(topic: string) {
  41. return this.topics[topic] && this.topics[topic].length > 0
  42. }
  43. }
  44. // 实例化并导出单例
  45. export default new PubsubService()