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"
|
// Connects to data-controller="unsaved-changes"
|
||||||
export default class extends Controller {
|
export default class extends Controller {
|
||||||
changed = false
|
originalFormData = null
|
||||||
|
|
||||||
connect() {
|
connect() {
|
||||||
window.addEventListener("beforeunload", (event) => {
|
this.originalFormData = this.formState()
|
||||||
this.leavingPage(event);
|
|
||||||
});
|
window.addEventListener("beforeunload", (event) => this.leavingPage(event))
|
||||||
document.addEventListener('turbo:before-visit', (event) => {
|
document.addEventListener('turbo:before-visit', (e) => this.leavingPage(e));
|
||||||
this.leavingPage(event);
|
this.element.addEventListener("submit", _ => this.originalFormData = this.formState())
|
||||||
});
|
|
||||||
this.element.addEventListener("submit", (_) => {
|
|
||||||
this.changed = false
|
|
||||||
})
|
|
||||||
this.element.addEventListener("change", (_) => {
|
|
||||||
this.changed = true
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
formState() {
|
||||||
|
return JSON.stringify(new FormData(this.element).values().toArray().filter(x => x != ""))
|
||||||
|
}
|
||||||
|
|
||||||
leavingPage(event) {
|
leavingPage(event) {
|
||||||
if(!this.changed) {
|
if(this.originalFormData == this.formState()) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("leavingPage", this.changed)
|
|
||||||
if (event.type == "turbo:before-visit") {
|
if (event.type == "turbo:before-visit") {
|
||||||
if (!window.confirm("Es gibt ungespeicherte Änderungen! Wirklich verlassen?")) {
|
if (!window.confirm("Es gibt ungespeicherte Änderungen! Wirklich verlassen?")) {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue