-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathevent.js
44 lines (42 loc) · 974 Bytes
/
event.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
const eventListener = {
clients: {},
listen: function (key, func) {
if (!this.clients[key]) {
this.clients[key] = [];
}
this.clients[key].push(func);
},
trigger: function () {
const key = Array.prototype.shift.call(arguments);
const funcs = this.clients[key];
if (!funcs || funcs.length == 0) {
return false;
}
for (let i = 0; func = funcs[i++];) {
func.apply(this, arguments);
}
},
remove: function (key, func) {
const funcs = this.clients[key];
if (!funcs) {
return false;
}
if (!func) {
funcs && (funcs.length = 0);
} else {
for (let i = funcs.length - 1; i >= 0; i--) {
const _func = funcs[i];
if (_func === func) {
funcs.splice(i, 1);
}
}
}
}
}
const installEventListener = (obj) => {
for (const key in eventListener) {
obj[key] = eventListener[key];
}
return obj;
}
module.exports = {installEventListener};