-
Notifications
You must be signed in to change notification settings - Fork 0
/
emitter.js
45 lines (42 loc) · 999 Bytes
/
emitter.js
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
import {
isFunction,
isUnset,
} from "mytoolkit"
class emitter {
constructor() {
this.listeners = {}
}
on(type, func) {
let listenersByType = this.listeners[type]
!listenersByType && (this.listeners[type] = listenersByType = [])
// find previous func with same id
if (!listenersByType.find(l => l === func)) {
listenersByType.push(func)
}
}
off(type, func) {
let listenersByType = this.listeners[type]
if (listenersByType && isFunction(func)) {
listenersByType = listenersByType.filter(l => l !== func)
}
}
emit(type, ...arg) {
let listenersByType = this.listeners[type]
if (listenersByType) {
listenersByType.forEach(l => {
l(...arg)
})
}
}
clear(type) {
if (isUnset(type)) {
this.listeners = {}
return
}
let listenersByType = this.listeners[type]
if (listenersByType && listenersByType.length) {
this.listeners[type] = []
}
}
}
export default emitter