-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
73 lines (61 loc) · 1.59 KB
/
index.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import type from 'type-detect'
class EventRegister {
static _Listeners = {
count: 0,
refs: {},
}
static addEventListener(eventName, callback) {
if (
type(eventName) === 'string' &&
type(callback) === 'function'
) {
EventRegister._Listeners.count++
const eventId = 'l' + EventRegister._Listeners.count
EventRegister._Listeners.refs[eventId] = {
name: eventName,
callback,
}
return eventId
}
return false
}
static removeEventListener(id) {
if (type(id) === 'string') {
return delete EventRegister._Listeners.refs[id]
}
return false
}
static removeAllListeners() {
let removeError = false
Object.keys(EventRegister._Listeners.refs).forEach(_id => {
const removed = delete EventRegister._Listeners.refs[_id]
removeError = (!removeError) ? !removed : removeError
})
return !removeError
}
static emitEvent(eventName, data) {
Object.keys(EventRegister._Listeners.refs).forEach(_id => {
if (
EventRegister._Listeners.refs[_id] &&
eventName === EventRegister._Listeners.refs[_id].name
)
EventRegister._Listeners.refs[_id].callback(data)
})
}
/*
* shortener
*/
static on(eventName, callback) {
return EventRegister.addEventListener(eventName, callback)
}
static rm(eventName) {
return EventRegister.removeEventListener(eventName)
}
static rmAll() {
return EventRegister.removeAllListeners()
}
static emit(eventName, data) {
EventRegister.emitEvent(eventName, data)
}
}
export { EventRegister }