Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
NebulaServices
GitHub Repository: NebulaServices/Nebula
Path: blob/main/src/utils/events.ts
976 views
1
type Event = "astro:page-load" | "astro:before-swap" | "astro:after-swap" | "DOMContentLoaded";
2
interface Events {
3
events: {
4
"astro:page-load"?: () => unknown;
5
"astro:before-swap"?: () => unknown;
6
"astro:after-swap"?: () => unknown;
7
"DOMContentLoaded"?: () => unknown;
8
};
9
logging: boolean;
10
}
11
12
/**
13
* This class creates an event handler for us with optional logging
14
*
15
* @example
16
* const eventHandler = new EventHandler({
17
* events: {
18
* "astro:page-load": () => { console.log("After page load") },
19
* "astro:before-swap": () => {},
20
* "astro:after-swap": () => {},
21
* "DOMContentLoaded": () => {}
22
* }, // Pass any number of these : D (they are all optional)
23
* logging: false // Set this to true to enable logging when things go wrong.
24
* });
25
*
26
* eventHandler.bind(); // Attaches every event you passed.
27
*/
28
class EventHandler {
29
#eventItems: Events;
30
constructor(items: Events) {
31
this.#eventItems = items;
32
}
33
#attachEvent(items: Events, eventType: Event, fn: () => unknown) {
34
if (items.logging) return document.addEventListener(eventType, async () => await fn());
35
document.addEventListener(eventType, async () => {
36
try {
37
await fn();
38
}
39
catch (_) {}
40
});
41
}
42
/**
43
* Binds the events you passed when creating the class to the document. If none are passed, an error is thrown.
44
*/
45
bind(): void | Error {
46
const events = Object.entries(this.#eventItems.events);
47
if (!events || events.length === 0) throw new Error('No events added!');
48
events.map((event) => {
49
this.#attachEvent(this.#eventItems, event[0] as Event, event[1]);
50
});
51
}
52
}
53
54
export { EventHandler, type Events }
55
56