-
-
Notifications
You must be signed in to change notification settings - Fork 652
Expand file tree
/
Copy pathevented.ts
More file actions
95 lines (81 loc) · 2.25 KB
/
evented.ts
File metadata and controls
95 lines (81 loc) · 2.25 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
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
import { isUndefined } from './utils/type-check.ts';
export type Bindings = {
[key: string]: Array<{ handler: () => void; ctx?: unknown; once?: boolean }>;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type AnyHandler = (...args: any[]) => void;
export class Evented {
declare bindings: Bindings;
/**
* Adds an event listener for the given event string.
*
* @param {string} event
* @param {Function} handler
* @param ctx
* @param {boolean} once
* @returns
*/
on(event: string, handler: AnyHandler, ctx?: unknown, once = false) {
if (isUndefined(this.bindings)) {
this.bindings = {};
}
if (isUndefined(this.bindings[event])) {
this.bindings[event] = [];
}
this.bindings[event]?.push({ handler, ctx, once });
return this;
}
/**
* Adds an event listener that only fires once for the given event string.
*
* @param {string} event
* @param {Function} handler
* @param ctx
* @returns
*/
once(event: string, handler: AnyHandler, ctx?: unknown) {
return this.on(event, handler, ctx, true);
}
/**
* Removes an event listener for the given event string.
*
* @param {string} event
* @param {Function} handler
* @returns
*/
off(event: string, handler?: AnyHandler) {
if (isUndefined(this.bindings) || isUndefined(this.bindings[event])) {
return this;
}
if (isUndefined(handler)) {
delete this.bindings[event];
} else {
this.bindings[event]?.forEach((binding, index) => {
if (binding.handler === handler) {
this.bindings[event]?.splice(index, 1);
}
});
}
return this;
}
/**
* Triggers an event listener for the given event string.
*
* @param {string} event
* @returns
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
trigger(event: string, ...args: any[]) {
if (!isUndefined(this.bindings) && this.bindings[event]) {
this.bindings[event]?.slice().forEach((binding, index) => {
const { ctx, handler, once } = binding;
const context = ctx || this;
handler.apply(context, args as []);
if (once) {
this.bindings[event]?.splice(index, 1);
}
});
}
return this;
}
}