Retrospring/app/javascript/retrospring/utilities/registerEvents.ts

30 lines
1.1 KiB
TypeScript
Raw Normal View History

import { on, OnCallbackFunction } from './on';
2021-08-11 05:10:24 -07:00
export interface EventDef {
2021-08-10 04:16:40 -07:00
type: string;
target: Node | NodeList | string;
2021-08-10 04:16:40 -07:00
handler: EventListenerOrEventListenerObject;
global?: boolean;
2021-08-10 04:16:40 -07:00
}
export default function registerEvents(events: EventDef[]): void {
events.forEach(event => {
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');
}
2021-08-10 04:16:40 -07:00
});
} else if (event.target instanceof Node) {
if (!(event.target as HTMLElement).classList.contains('js-initialized')) {
event.target.addEventListener(event.type, event.handler);
(event.target as HTMLElement).classList.add('js-initialized');
}
2021-08-10 04:16:40 -07:00
}
});
}