-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub.js
63 lines (49 loc) · 1.13 KB
/
pubsub.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
// tags: #event #design-mode #hot
class PubSub {
#evts = {};
on(e, cb) {
if (!e || !cb) return;
this.#evts[e] ? this.#evts[e].push(cb) : (this.#evts[e] = [cb]);
}
once(e, cb) {
if (!e || !cb) return;
const wrapper = (...params) => {
cb(...params);
this.off(e, wrapper);
};
this.on(e, wrapper);
}
off(e, cb) {
if (!this.#has(e) || !cb) return;
if (cb === "*") {
delete this.#evts[e];
return;
}
this.#evts[e] = this.#evts[e].filter((i) => i !== cb);
!this.#evts[e].length && delete this.#evts[e];
}
emit(e, ...params) {
if (!this.#has(e)) return;
this.#evts[e].forEach((i) => i(...params));
}
#has(e) {
return this.#evts[e];
}
get debug() {
return this.#evts;
}
}
/* test code */
const assert = require("node:assert/strict");
const pubsub = new PubSub();
pubsub.on("event", () => {
assert.ok(true);
});
pubsub.once("event", () => {
assert.ok(true);
});
assert.equal(pubsub.debug.event.length, 2);
pubsub.emit("event");
assert.equal(pubsub.debug.event.length, 1);
pubsub.off("event", "*");
assert.equal(pubsub.debug.event, undefined);