event.js
1.36 KB
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
class EventEmitter {
emit(event, ...args) {
this._stores = this._stores || {};
let store = this._stores[event];
let args;
if (store) {
store = [ ...store ];
args[0] = {
eventCode: event,
data: args[0],
};
for (const element of store) {
element.cb.apply(element.ctx, args);
}
}
}
off(event, fn) {
this._stores = this._stores || {};
// all
if (arguments.length === 0) {
this._stores = {};
return;
}
// specific event
const store = this._stores[event];
if (!store) return;
// remove all handlers
if (arguments.length === 1) {
return;
}
// remove specific handler
let cb;
for (let i = 0, len = store.length; i < len; i++) {
cb = store[i].cb;
if (cb === fn) {
store.splice(i, 1);
break;
}
}
}
on(event, fn, ctx) {
if (typeof fn !== "function") {
console.error("listener must be a function");
return;
}
this._stores = this._stores || {};
(this._stores[event] = this._stores[event] || []).push({ cb: fn, ctx });
}
}
module.exports = EventEmitter;