event

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
class EventEmitter {
constructor() {
this._events = new Map()
}
addListener(type, fn) {
const handler = this._events.get(type)
if (!handler) {
this._events.set(type, fn)
} else if (handler && typeof handler === 'function') {
this._events.set(type, [handler, fn])
} else {
handler.push(fn)
}
}
emit(type, ...args) {
let handler = this._events.get(type)
if (Array.isArray(handler)) {
for (let i = 0; i < handler.length; i++) {
if (!!args.length) {
handler[i].apply(this, args)
} else {
handler[i].call(this)
}
}
} else {
if (!!args.length) {
handler.apply(this, args)
} else {
handler.call(this)
}
}
return true
}
}

let emitter = new EventEmitter()
emitter.addListener('say', (what) => {
console.log(`say ${what}`)
})
emitter.addListener('say', (what) => {
console.log(`say ${what} too`)
})
emitter.emit('say', 'hello')