feat(stimulus): add onGlobal helper
This commit is contained in:
parent
0eeffb2a0c
commit
9b01b2cff9
1 changed files with 18 additions and 3 deletions
|
@ -15,7 +15,7 @@ export class ApplicationController extends Controller {
|
||||||
debounced();
|
debounced();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected globalDispatch(type: string, detail: Detail): void {
|
protected globalDispatch<T = Detail>(type: string, detail?: T): void {
|
||||||
this.dispatch(type, {
|
this.dispatch(type, {
|
||||||
detail,
|
detail,
|
||||||
prefix: '',
|
prefix: '',
|
||||||
|
@ -26,14 +26,29 @@ export class ApplicationController extends Controller {
|
||||||
protected on<HandlerEvent extends Event = Event>(
|
protected on<HandlerEvent extends Event = Event>(
|
||||||
eventName: string,
|
eventName: string,
|
||||||
handler: (event: HandlerEvent) => void
|
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 {
|
): void {
|
||||||
const disconnect = this.disconnect;
|
const disconnect = this.disconnect;
|
||||||
const callback = (event: Event): void => {
|
const callback = (event: Event): void => {
|
||||||
handler(event as HandlerEvent);
|
handler(event as HandlerEvent);
|
||||||
};
|
};
|
||||||
this.element.addEventListener(eventName, callback);
|
target.addEventListener(eventName, callback);
|
||||||
this.disconnect = () => {
|
this.disconnect = () => {
|
||||||
this.element.removeEventListener(eventName, callback);
|
target.removeEventListener(eventName, callback);
|
||||||
disconnect.call(this);
|
disconnect.call(this);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue