'f'
mh-two-thousand-and-two
2024-04-12 26f2711ef9461961fb953e2b497bd314ef95e345
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
export default class EventChannel {
  constructor (id, events) {
    this.id = id
    this.listener = {}
    this.emitCache = {}
    if (events) {
      Object.keys(events).forEach(name => {
        this.on(name, events[name])
      })
    }
  }
 
  emit (eventName, ...args) {
    const fns = this.listener[eventName]
    if (!fns) {
      return (this.emitCache[eventName] || (this.emitCache[eventName] = [])).push(args)
    }
    fns.forEach(opt => {
      opt.fn.apply(opt.fn, args)
    })
    this.listener[eventName] = fns.filter(opt => opt.type !== 'once')
  }
 
  on (eventName, fn) {
    this._addListener(eventName, 'on', fn)
    this._clearCache(eventName)
  }
 
  once (eventName, fn) {
    this._addListener(eventName, 'once', fn)
    this._clearCache(eventName)
  }
 
  off (eventName, fn) {
    const fns = this.listener[eventName]
    if (!fns) {
      return
    }
    if (fn) {
      for (let i = 0; i < fns.length;) {
        if (fns[i].fn === fn) {
          fns.splice(i, 1)
          i--
        }
        i++
      }
    } else {
      delete this.listener[eventName]
    }
  }
 
  _clearCache (eventName) {
    const cacheArgs = this.emitCache[eventName]
    if (cacheArgs) {
      for (; cacheArgs.length > 0;) {
        this.emit.apply(this, [eventName].concat(cacheArgs.shift()))
      }
    }
  }
 
  _addListener (eventName, type, fn) {
    (this.listener[eventName] || (this.listener[eventName] = [])).push({
      fn,
      type
    })
  }
}