Improve unsaved-changes controller
This commit is contained in:
parent
4f8b18ca25
commit
bd36984edf
1 changed files with 12 additions and 16 deletions
|
|
@ -2,29 +2,25 @@ import { Controller } from "@hotwired/stimulus"
|
|||
|
||||
// Connects to data-controller="unsaved-changes"
|
||||
export default class extends Controller {
|
||||
changed = false
|
||||
|
||||
originalFormData = null
|
||||
|
||||
connect() {
|
||||
window.addEventListener("beforeunload", (event) => {
|
||||
this.leavingPage(event);
|
||||
});
|
||||
document.addEventListener('turbo:before-visit', (event) => {
|
||||
this.leavingPage(event);
|
||||
});
|
||||
this.element.addEventListener("submit", (_) => {
|
||||
this.changed = false
|
||||
})
|
||||
this.element.addEventListener("change", (_) => {
|
||||
this.changed = true
|
||||
})
|
||||
this.originalFormData = this.formState()
|
||||
|
||||
window.addEventListener("beforeunload", (event) => this.leavingPage(event))
|
||||
document.addEventListener('turbo:before-visit', (e) => this.leavingPage(e));
|
||||
this.element.addEventListener("submit", _ => this.originalFormData = this.formState())
|
||||
}
|
||||
|
||||
formState() {
|
||||
return JSON.stringify(new FormData(this.element).values().toArray().filter(x => x != ""))
|
||||
}
|
||||
|
||||
leavingPage(event) {
|
||||
if(!this.changed) {
|
||||
if(this.originalFormData == this.formState()) {
|
||||
return
|
||||
}
|
||||
|
||||
console.log("leavingPage", this.changed)
|
||||
if (event.type == "turbo:before-visit") {
|
||||
if (!window.confirm("Es gibt ungespeicherte Änderungen! Wirklich verlassen?")) {
|
||||
event.preventDefault()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue