Extend `registerEvents` utility to accept global events

This commit is contained in:
Andreas Nedbal 2022-01-03 03:32:54 +01:00 committed by Andreas Nedbal
parent b2d430eb1e
commit aef180277c
1 changed files with 18 additions and 5 deletions

View File

@ -1,17 +1,30 @@
import { on, OnCallbackFunction } from './on';
export interface EventDef {
type: string;
target: Node | NodeList;
target: Node | NodeList | string;
handler: EventListenerOrEventListenerObject;
global?: boolean;
}
export default function registerEvents(events: EventDef[]): void {
events.forEach(event => {
if (event.target instanceof NodeList) {
event.target.forEach(element => {
element.addEventListener(event.type, event.handler);
if (event.global) {
if (typeof event.target === 'string') {
on(event.type, event.target, event.handler as OnCallbackFunction);
}
} else if (event.target instanceof NodeList) {
event.target.forEach((element: HTMLElement) => {
if (!element.classList.contains('js-initialized')) {
element.addEventListener(event.type, event.handler);
element.classList.add('js-initialized');
}
});
} else if (event.target instanceof Node) {
event.target.addEventListener(event.type, event.handler);
if (!(event.target as HTMLElement).classList.contains('js-initialized')) {
event.target.addEventListener(event.type, event.handler);
(event.target as HTMLElement).classList.add('js-initialized');
}
}
});
}