feat(stimulus): add onGlobal helper

This commit is contained in:
Paul Chavard 2022-05-06 19:44:33 +02:00
parent 0eeffb2a0c
commit 9b01b2cff9

View file

@ -15,7 +15,7 @@ export class ApplicationController extends Controller {
debounced();
}
protected globalDispatch(type: string, detail: Detail): void {
protected globalDispatch<T = Detail>(type: string, detail?: T): void {
this.dispatch(type, {
detail,
prefix: '',
@ -26,14 +26,29 @@ export class ApplicationController extends Controller {
protected on<HandlerEvent extends Event = Event>(
eventName: string,
handler: (event: HandlerEvent) => void
): 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);
};
this.element.addEventListener(eventName, callback);
target.addEventListener(eventName, callback);
this.disconnect = () => {
this.element.removeEventListener(eventName, callback);
target.removeEventListener(eventName, callback);
disconnect.call(this);
};
}