Reputation: 35
I have ts script with code to handle "unsaved"
text inputs
Here is code of script
export class Unsave {
public static unsave_check(): void {
let unsaved = false;
$(":input").change(function(){
unsaved = true;
console.log(unsaved);
});
function unloadPage(){
if(unsaved){
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
}
}
}
And then I use it in other script like this
`window.onbeforeunload = Unsave.unsave_check();`
But as I see, function unloadPage()
is never hit, why so?
I see that unsaved is changing value to true. But when I go back, I get no alert message.
How I can fix this issue?
thank's for help
Upvotes: 0
Views: 1097
Reputation: 3568
You should call unloadPage
in window.onbeforeunload
with something like this :
export class Unsave {
private static unsaved: boolean = false;
public static unsave_check(): void {
Unsave.unsaved = false;
$(":input").change(function(){
Unsave.unsaved = true;
console.log(Unsave.unsaved);
});
}
public static unloadPage(): string {
if(Unsave.unsaved){
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
}
}
Then
window.onbeforeunload = Unsave.unloadPage();
and somewhere else in your code you have to call unsave_check
...
For instance:
document.addEventListener("DOMContentLoaded", function() {
Unsave.unsave_check();
});
Note: unloadPage
and unsave_check
are not consistent naming... one camel case, one snake case ?
Upvotes: 0
Reputation: 1317
I think you should call Unsave.unsave_check()
when the form has been initialized and bind the unloadPage
on the window.onbeforeunload
(and you can make it also static - or the other method to non-static and instantiate the object).
You should also move the value unsaved
from the function scope, maybe to a private class field so both methods can access it
export class Unsave {
private unsaved: boolean = false;
public register() {
$(":input").change(() => {
this.unsaved = true;
console.log(this.unsaved);
});
}
public unloadPage() {
if (this.unsaved) {
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
}
}
// call this after form init
const unsaveChecker = new Unsave();
unsaveChecker.register()
window.onbeforeunload = () => unsaveChecker.unloadPage()
Upvotes: 1