32 lines
No EOL
928 B
JavaScript
32 lines
No EOL
928 B
JavaScript
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 {
|
|
initialState = null
|
|
|
|
connect() {
|
|
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.initialState = this.formState())
|
|
}
|
|
|
|
formState() {
|
|
return JSON.stringify(Array.from(new FormData(this.element).entries())
|
|
.filter(x => x[1] != "")
|
|
.sort(x => x[0]))
|
|
}
|
|
|
|
leavingPage(event) {
|
|
if(this.initialState == this.formState()) {
|
|
return
|
|
}
|
|
|
|
if (!window.confirm(LEAVE_ALERT)) {
|
|
event.preventDefault()
|
|
}
|
|
}
|
|
} |