简体   繁体   中英

Alert when leaving page with unsaved form(typescript)

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

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()

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM