-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMemo.js
73 lines (63 loc) · 1.58 KB
/
Memo.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
let listeners = {};
export default class Memo {
static on(event, handler, eventListeners = listeners) {
if (eventListeners[event] === undefined) {
eventListeners[event] = [handler];
} else {
eventListeners[event].push(handler);
}
}
static off(event, handler, eventListeners = listeners) {
if (eventListeners[event]) {
for (let i = eventListeners[event].length - 1; i >= 0; i--) {
if (eventListeners[event].length === 1) {
delete eventListeners[event];
} else {
eventListeners[event].splice(i, 1);
break;
}
}
}
}
static trigger(event) {
var data = new Array(...arguments);
data.splice(0, 1);
Memo.send(event, listeners, data)
}
static send(event, eventListeners = listeners, data) {
if (eventListeners[event]) {
for (let i = eventListeners[event].length - 1; i >= 0; i--) {
if (eventListeners[event] !== undefined) {
if (typeof eventListeners[event][i] === "function" && eventListeners[event][i]) {
eventListeners[event][i](...data);
} else {
throw "Event handler is not a function.";
}
}
}
}
}
static unbindAll(eventListeners = listeners) {
for (const event in eventListeners) {
delete eventListeners[event];
}
return true;
};
constructor() {
this.listeners = {};
}
on(event, handler) {
Memo.on(event, handler, this.listeners);
}
off(event, handler) {
Memo.off(event, handler, this.listeners);
}
trigger(event) {
var data = new Array(...arguments);
data.splice(0, 1);
Memo.send(event, this.listeners, data);
}
unbindAll() {
Memo.unbindAll(this.listeners);
};
}