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 {
|
export interface EventDef {
|
||||||
type: string;
|
type: string;
|
||||||
target: Node | NodeList;
|
target: Node | NodeList | string;
|
||||||
handler: EventListenerOrEventListenerObject;
|
handler: EventListenerOrEventListenerObject;
|
||||||
|
global?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function registerEvents(events: EventDef[]): void {
|
export default function registerEvents(events: EventDef[]): void {
|
||||||
events.forEach(event => {
|
events.forEach(event => {
|
||||||
if (event.target instanceof NodeList) {
|
if (event.global) {
|
||||||
event.target.forEach(element => {
|
if (typeof event.target === 'string') {
|
||||||
element.addEventListener(event.type, event.handler);
|
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) {
|
} 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