From 7e3dbe3201109033b14a9c25d27f80566ae572e1 Mon Sep 17 00:00:00 2001 From: MrExplode Date: Tue, 20 Feb 2024 14:00:52 +0100 Subject: [PATCH] feat: mutation observer wrapper --- src/observer.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/observer.ts diff --git a/src/observer.ts b/src/observer.ts new file mode 100644 index 0000000..9822b0a --- /dev/null +++ b/src/observer.ts @@ -0,0 +1,17 @@ +const config: MutationObserverInit = { attributes: true, childList: true, subtree: true } + +/** + * Creates a mutation observer. + * + * @param selector the query selector for target nodes + * @param mutationCallback the event callback for mutations + * @returns a callback for unsubscribing from the events + */ +export function observe( + selector: string, + mutationCallback: (mutations: MutationRecord[]) => void +): () => void { + const observer = new MutationObserver(mutationCallback) + observer.observe(document.querySelector(selector)!, config) + return () => observer.disconnect() +}