From af5d65366d14bb21e39e125c0193054d79e47ccd Mon Sep 17 00:00:00 2001 From: HelgiMagic <113669521+HelgiMagic@users.noreply.github.com> Date: Thu, 26 Dec 2024 22:05:50 +0300 Subject: [PATCH] Create dynamicListener.ts --- dynamicListener.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 dynamicListener.ts diff --git a/dynamicListener.ts b/dynamicListener.ts new file mode 100644 index 0000000..37e3b80 --- /dev/null +++ b/dynamicListener.ts @@ -0,0 +1,37 @@ +type EventCallback = (this: any, event: Event) => void; + +function getConditionalCallback(selector: string, callback: EventCallback): EventCallback { + return function (e: Event) { + if (e.target && (e.target as Element).matches(selector)) { + (e as any).delegatedTarget = e.target; + callback.call(this, e); + return; + } + + const path = (e as any).path || (e.composedPath && e.composedPath()); + if (!path) return; + + for (let i = 0; i < path.length; ++i) { + const el = path[i] as Element; + if (el.matches && el.matches(selector)) { + (e as any).delegatedTarget = el; + callback.call(this, e); + } + if (el === e.currentTarget) { + return; + } + } + }; +} + +export default function addDynamicEventListener( + rootElement: Element, + eventType: string, + selector: string, + callback: EventCallback, + options: boolean | AddEventListenerOptions = false +): () => void { + const cb = getConditionalCallback(selector, callback); + rootElement.addEventListener(eventType, cb, options); + return () => rootElement.removeEventListener(eventType, cb, options); +}