page size and unsaved changes contr. refactor
This commit is contained in:
parent
9b521c1f2b
commit
5bd0cf7ae0
2 changed files with 12 additions and 16 deletions
|
|
@ -1,36 +1,32 @@
|
|||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
const LEAVE_ALERT = "Es gibt ungespeicherte Änderungen! Wirklich verlassen?"
|
||||
|
||||
// Connects to data-controller="unsaved-changes"
|
||||
export default class extends Controller {
|
||||
originalFormData = null
|
||||
initialState = null
|
||||
|
||||
connect() {
|
||||
this.originalFormData = this.formState()
|
||||
this.initialState = 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())
|
||||
document.addEventListener('turbo:before-visit', (e) => this.leavingPage(e))
|
||||
this.element.addEventListener("submit", (_) => this.initialState = this.formState())
|
||||
}
|
||||
|
||||
formState() {
|
||||
return JSON.stringify(Array.from(new FormData(this.element).entries())
|
||||
.filter(x => x[1] != ""))
|
||||
.filter(x => x[1] != "")
|
||||
.sort(x => x[0]))
|
||||
}
|
||||
|
||||
leavingPage(event) {
|
||||
if(this.originalFormData == this.formState()) {
|
||||
if(this.initialState == this.formState()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (event.type == "turbo:before-visit") {
|
||||
if (!window.confirm("Es gibt ungespeicherte Änderungen! Wirklich verlassen?")) {
|
||||
event.preventDefault()
|
||||
}
|
||||
} else {
|
||||
if (!window.confirm("Es gibt ungespeicherte Änderungen! Wirklich verlassen?")) {
|
||||
event.preventDefault()
|
||||
}
|
||||
return event.returnValue;
|
||||
if (!window.confirm(LEAVE_ALERT)) {
|
||||
event.preventDefault()
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue