demarches-normaliennes/app/javascript/controllers/application_controller.ts

56 lines
1.5 KiB
TypeScript
Raw Normal View History

import { Controller } from '@hotwired/stimulus';
import { debounce } from '@utils';
export type Detail = Record<string, unknown>;
export class ApplicationController extends Controller {
#debounced = new Map<() => void, () => void>();
protected debounce(fn: () => void, interval: number): void {
let debounced = this.#debounced.get(fn);
if (!debounced) {
debounced = debounce(fn.bind(this), interval);
this.#debounced.set(fn, debounced);
}
debounced();
}
2022-05-06 19:44:33 +02:00
protected globalDispatch<T = Detail>(type: string, detail?: T): void {
this.dispatch(type, {
detail,
prefix: '',
target: document.documentElement
});
}
protected on<HandlerEvent extends Event = Event>(
eventName: string,
handler: (event: HandlerEvent) => void
2022-05-06 19:44:33 +02:00
): void {
this.onTarget(this.element, eventName, handler);
}
protected onGlobal<HandlerEvent extends Event = Event>(
eventName: string,
handler: (event: HandlerEvent) => void
): void {
this.onTarget(document.documentElement, eventName, handler);
}
private onTarget<HandlerEvent extends Event = Event>(
target: EventTarget,
eventName: string,
handler: (event: HandlerEvent) => void
): void {
const disconnect = this.disconnect;
const callback = (event: Event): void => {
handler(event as HandlerEvent);
};
2022-05-06 19:44:33 +02:00
target.addEventListener(eventName, callback);
this.disconnect = () => {
2022-05-06 19:44:33 +02:00
target.removeEventListener(eventName, callback);
disconnect.call(this);
};
}
}