diff --git a/app/javascript/controllers/application_controller.ts b/app/javascript/controllers/application_controller.ts index ca753e1f4..54cfcd3a5 100644 --- a/app/javascript/controllers/application_controller.ts +++ b/app/javascript/controllers/application_controller.ts @@ -15,7 +15,7 @@ export class ApplicationController extends Controller { debounced(); } - protected globalDispatch(type: string, detail: Detail): void { + protected globalDispatch(type: string, detail?: T): void { this.dispatch(type, { detail, prefix: '', @@ -26,14 +26,29 @@ export class ApplicationController extends Controller { protected on( eventName: string, handler: (event: HandlerEvent) => void + ): void { + this.onTarget(this.element, eventName, handler); + } + + protected onGlobal( + eventName: string, + handler: (event: HandlerEvent) => void + ): void { + this.onTarget(document.documentElement, eventName, handler); + } + + private onTarget( + 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); }; }