-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
59 lines (54 loc) · 1.7 KB
/
mod.ts
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
export class CustomEventTarget<
E extends { [type: string]: unknown },
> extends EventTarget {
constructor() {
super();
}
dispatchEvent<T extends E[keyof E]>(event: Event | CustomEvent<T>): boolean {
const originalDispatchEvent = super.dispatchEvent;
const { type } = event;
if ('detail' in event && type !== '*') { // do not dispatch events with explicit '*' type twice
const asteriskEvent = new CustomEvent('*', { detail: event.detail });
originalDispatchEvent.call(this, asteriskEvent);
}
return originalDispatchEvent.call(this, event);
}
emit<K extends keyof E>(
type: K,
detail?: E[K],
options?: EventInit,
): boolean {
if (typeof type !== 'string') throw new Error('Invalid event type');
const event = new CustomEvent(type, {
...options,
detail,
});
return this.dispatchEvent(event);
}
all<T extends E[keyof E]>(allEventsListener: (detail: T) => void) {
const listener = (evt: CustomEvent<T> | Event) => {
if ('detail' in evt) allEventsListener(evt.detail);
};
this.addEventListener('*', listener);
return listener;
}
on<K extends keyof E>(
type: K,
customEventListener: (detail: E[K]) => void,
) {
if (typeof type !== 'string') throw new Error('Invalid event type');
const listener = (evt: CustomEvent<E[K]> | Event) => {
if ('detail' in evt) customEventListener(evt.detail);
};
this.addEventListener(type, listener);
return listener;
}
off<K extends keyof E>(
type: K,
listener: (evt: Event) => void,
): this {
if (typeof type !== 'string') throw new Error('Invalid event type');
this.removeEventListener(type, listener);
return this;
}
}