Merge pull request #8430 from tchak/refactor-on-with-target

feat(stimulus): allow `on` with target
This commit is contained in:
Paul Chavard 2023-01-16 16:55:16 +01:00 committed by GitHub
commit bdd0ab0a22
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 7 deletions

View file

@ -1,5 +1,6 @@
import { Controller } from '@hotwired/stimulus';
import debounce from 'debounce';
import invariant from 'tiny-invariant';
export type Detail = Record<string, unknown>;
@ -39,10 +40,27 @@ export class ApplicationController extends Controller {
}
protected on<HandlerEvent extends Event = Event>(
target: EventTarget,
eventName: string,
handler: (event: HandlerEvent) => void
): void;
protected on<HandlerEvent extends Event = Event>(
eventName: string,
handler: (event: HandlerEvent) => void
): void;
protected on<HandlerEvent extends Event = Event>(
targetOrEventName: EventTarget | string,
eventNameOrHandler: string | ((event: HandlerEvent) => void),
handler?: (event: HandlerEvent) => void
): void {
this.onTarget(this.element, eventName, handler);
if (typeof targetOrEventName == 'string') {
invariant(typeof eventNameOrHandler != 'string', 'handler is required');
this.onTarget(this.element, targetOrEventName, eventNameOrHandler);
} else {
invariant(eventNameOrHandler == 'string', 'event name is required');
invariant(handler, 'handler is required');
this.onTarget(targetOrEventName, eventNameOrHandler, handler);
}
}
protected onGlobal<HandlerEvent extends Event = Event>(

View file

@ -21,7 +21,7 @@ export class ReplaceAttachmentController extends ApplicationController {
// reset autoAttachUrl which would add an attachment
// when replace is not finalized
this.inputTarget.addEventListener('cancel', () => {
this.on(this.inputTarget, 'cancel', () => {
this.inputTarget.dataset.autoAttachUrl =
this.inputTarget.dataset.originalAutoAttachUrl;
});

View file

@ -9,12 +9,12 @@ export class SupportController extends ApplicationController {
connect() {
this.inputRadioTargets.forEach((inputRadio) => {
inputRadio.addEventListener('change', this.onChange.bind(this));
inputRadio.addEventListener('keydown', this.onChange.bind(this));
this.on(inputRadio, 'change', this.onChange.bind(this));
this.on(inputRadio, 'keydown', this.onChange.bind(this));
});
}
onChange(event: Event) {
private onChange(event: Event) {
const target = event.target as HTMLInputElement;
const content = this.getContentForTarget(target);
@ -29,12 +29,12 @@ export class SupportController extends ApplicationController {
}
}
getLabelForTarget(target: HTMLInputElement) {
private getLabelForTarget(target: HTMLInputElement) {
const labelSelector = `label[for="${target.id}"]`;
return document.querySelector(labelSelector);
}
getContentForTarget(target: HTMLInputElement) {
private getContentForTarget(target: HTMLInputElement) {
const label = this.getLabelForTarget(target);
if (!label) {
return null;