@stimulus-library/controllers
Version:
A library of useful controllers for Stimulus
37 lines (36 loc) • 1.22 kB
JavaScript
import { BaseController, isHTMLAnchorElement, isHTMLFormElement, isTypeOfButtonableElement } from "@stimulus-library/utilities";
import { useEventListener } from "@stimulus-library/mixins";
export class ConfirmController extends BaseController {
get _message() {
return this.hasMessageValue ? this.messageValue : "Are you sure?";
}
get _eventType() {
if (isHTMLFormElement(this.el)) {
return "submit";
}
else if (isTypeOfButtonableElement(this.el)) {
return "click";
}
else if (isHTMLAnchorElement(this.el)) {
return "click";
}
else {
console.log("Can't handle confirmation on attached element", this.el);
throw new Error("Can't handle confirmation on attached element");
}
}
connect() {
requestAnimationFrame(() => {
useEventListener(this, this.el, this._eventType, this.confirm);
});
}
confirm(event) {
if (!(window.confirm(this._message))) {
event.preventDefault();
this.dispatchEvent(this.el, this.eventName("cancelled"));
}
}
}
ConfirmController.values = {
message: String,
};