| 1 |
/** |
| 2 |
* Minimal event handler |
| 3 |
*/ |
| 4 |
export class Events<T = string> { |
| 5 |
private events: Map<T, (() => void)[]>; |
| 6 |
|
| 7 |
constructor() { |
| 8 |
this.events = new Map<T, (() => void)[]>(); |
| 9 |
} |
| 10 |
|
| 11 |
/** |
| 12 |
* Register an event listener. |
| 13 |
* |
| 14 |
* @returns A function to remove the event listener. |
| 15 |
*/ |
| 16 |
on(event: T, callback: () => void): () => void { |
| 17 |
const events = this.events.get(event) ?? []; |
| 18 |
this.events.set(event, [...events, callback]); |
| 19 |
|
| 20 |
return () => { |
| 21 |
this.remove(event, callback); |
| 22 |
}; |
| 23 |
} |
| 24 |
|
| 25 |
/** |
| 26 |
* Register an event listener that will only be executed once. |
| 27 |
*/ |
| 28 |
once(event: T, callback: () => void): void { |
| 29 |
const runOnce = () => { |
| 30 |
this.remove(event, runOnce); |
| 31 |
callback(); |
| 32 |
}; |
| 33 |
|
| 34 |
this.on(event, runOnce); |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Remove an event listener. |
| 39 |
*/ |
| 40 |
remove(event: T, callback: () => void): void { |
| 41 |
const events = this.events.get(event); |
| 42 |
if (events) { |
| 43 |
this.events.set( |
| 44 |
event, |
| 45 |
events.filter((c) => c !== callback), |
| 46 |
); |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Trigger all listeners for an event. |
| 52 |
*/ |
| 53 |
trigger(event: T): void { |
| 54 |
const events = this.events.get(event); |
| 55 |
events?.forEach((callback) => { |
| 56 |
callback(); |
| 57 |
}); |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Execute the callback of the event of given type is fired on something |
| 63 |
* matching selector. |
| 64 |
* |
| 65 |
* @param element - The ancestor element that the listener will be attached to. |
| 66 |
* @param type - The event type to listen to. |
| 67 |
* @param selector - The DOM selector to match. |
| 68 |
* @param callback - The event listener to execute on a match. |
| 69 |
*/ |
| 70 |
export function delegate( |
| 71 |
element: HTMLElement | Document, |
| 72 |
type: string, |
| 73 |
selector: string, |
| 74 |
callback: (e: Event, c: Element) => void, |
| 75 |
): void { |
| 76 |
element.addEventListener(type, (event) => { |
| 77 |
let { target } = event; |
| 78 |
if (!(target instanceof Node)) { |
| 79 |
return; |
| 80 |
} |
| 81 |
if (!(target instanceof Element)) { |
| 82 |
target = target.parentNode; |
| 83 |
} |
| 84 |
if (target instanceof Element) { |
| 85 |
const closest = target.closest(selector); |
| 86 |
if (closest) { |
| 87 |
callback(event, closest); |
| 88 |
} |
| 89 |
} |
| 90 |
}); |
| 91 |
} |