1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 观察者模式
class EventBus {
    constructor() {
      // 消息中心,记录了所有的事件 以及 事件对应的处理函数
      this.subs = Object.create(null)
    }
   
    // 注册时间
    // 参数:1.事件名称  2.事件处理函数
    register(eventType, handler) {
      this.subs[eventType] = this.subs[eventType] || []
      this.subs[eventType].push(handler)
    }
   
    // 触发事件
    // 参数: 1.事件名称 2.接收的参数
    emit(eventType, ...ars) {
      if(this.subs[eventType]) {
        this.subs[eventType].forEach(handler => {
          handler(...ars)
        })
      }
    }
  }
   
  export default new EventBus()