-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
index.js
106 lines (86 loc) · 2.3 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
function Emitter(object) {
if (object) {
return mixin(object);
}
this._callbacks = new Map();
}
function mixin(object) {
Object.assign(object, Emitter.prototype);
object._callbacks = new Map();
return object;
}
Emitter.prototype.on = function (event, listener) {
const callbacks = this._callbacks.get(event) ?? [];
callbacks.push(listener);
this._callbacks.set(event, callbacks);
return this;
};
Emitter.prototype.once = function (event, listener) {
const on = (...arguments_) => {
this.off(event, on);
listener.apply(this, arguments_);
};
on.fn = listener;
this.on(event, on);
return this;
};
Emitter.prototype.off = function (event, listener) {
if (event === undefined && listener === undefined) {
this._callbacks.clear();
return this;
}
if (listener === undefined) {
this._callbacks.delete(event);
return this;
}
const callbacks = this._callbacks.get(event);
if (callbacks) {
for (const [index, callback] of callbacks.entries()) {
if (callback === listener || callback.fn === listener) {
callbacks.splice(index, 1);
break;
}
}
if (callbacks.length === 0) {
this._callbacks.delete(event);
} else {
this._callbacks.set(event, callbacks);
}
}
return this;
};
Emitter.prototype.emit = function (event, ...arguments_) {
const callbacks = this._callbacks.get(event);
if (callbacks) {
// Create a copy of the callbacks array to avoid issues if it's modified during iteration
const callbacksCopy = [...callbacks];
for (const callback of callbacksCopy) {
callback.apply(this, arguments_);
}
}
return this;
};
Emitter.prototype.listeners = function (event) {
return this._callbacks.get(event) ?? [];
};
Emitter.prototype.listenerCount = function (event) {
if (event) {
return this.listeners(event).length;
}
let totalCount = 0;
for (const callbacks of this._callbacks.values()) {
totalCount += callbacks.length;
}
return totalCount;
};
Emitter.prototype.hasListeners = function (event) {
return this.listenerCount(event) > 0;
};
// Aliases
Emitter.prototype.addEventListener = Emitter.prototype.on;
Emitter.prototype.removeListener = Emitter.prototype.off;
Emitter.prototype.removeEventListener = Emitter.prototype.off;
Emitter.prototype.removeAllListeners = Emitter.prototype.off;
if (typeof module !== 'undefined') {
module.exports = Emitter;
}