Extend `registerEvents` utility to accept global events
This commit is contained in:
parent
b2d430eb1e
commit
aef180277c
|
@ -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');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
Loading…
Reference in New Issue