tanghaolin
2022-08-31 244c4241427b9f3316f06f1e0ae2ee571edc1a23
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
27
28
29
30
31
32
33
34
35
36
37
38
39
class EventBus {
  constructor() {
    this._eventContainer = {};
  }
  // 添加监听事件
  on(type, fn) {
    this._eventContainer[type] = this._eventContainer[type] || [];
    this._eventContainer[type].push(fn);
    return this;
  }
 
  // 删除监听事件
  off(type, fn) {
    if(this._eventContainer[type]) {
      let index = this._eventContainer[type].indexOf(fn);
      index >=0 && this._eventContainer[type].splice(index, 1);
    }
    return this;
  }
 
  // 触发监听事件
  trigger(type, ...args) {
    if (type && this._eventContainer[type]) {
      [...this._eventContainer[type]].forEach((fn)=> {
        fn.apply(null, args);
      })
    }
    return this;
  }
 
  // reset
  reset() {
    this._eventContainer = {};
  }
}
 
const eventBus = new EventBus();
 
export default eventBus;