@stimulus-library/controllers
Version:
A library of useful controllers for Stimulus
25 lines (24 loc) • 865 B
JavaScript
import { BaseController } from "@stimulus-library/utilities";
import { useCollectionEventListener } from "@stimulus-library/mixins";
export class CheckboxXORController extends BaseController {
connect() {
useCollectionEventListener(this, this.checkboxTargets, "change", this._update);
}
_otherCheckboxes(el) {
return Array.from(this.checkboxTargets).filter(field => field !== el);
}
_update(event) {
const target = event.target;
if (!target) {
throw new Error("No target found on event");
}
const others = this._otherCheckboxes(target);
if (target.checked) {
others.forEach(checkbox => {
checkbox.checked = false;
this.dispatchEvent(this.el, "change");
});
}
}
}
CheckboxXORController.targets = ["checkbox"];