Question

I have a single page application written in MVC4 that uses pjax() to push html into various s in my page. I have one sub-form that allows the user to edit the data and it if the user changes the data an isDirty flag gets set in javascript to trigger an alert at the bottom of the page that there are un-saved updates. I would also like to implement an additional warning when the user tries to leave the page without saving. If I use a traditional onbeforeunload function like this

window.onbeforeunload = function() {
    if (isDirty) {
        return 'You have unsaved changes!';
    }
    return null;
};

it calls the alert if I try to close the page or navigate away from the site entirely but if the user clicks on one of my links that re-populates the with some different information it does not trigger because you are not actually leaving the page. How can I architect it so that one of these pjax() links causes an alert similar to if I close the page?

Was it helpful?

Solution

You could subscribe to a global event that fires before a pjax request:

$(document).on('pjax:beforeSend', function() { 
    if (isDirty) {
        return confirm('You have unsaved changes! Are you sure you want to continue?');
    }
    return true;
});

OTHER TIPS

You could add a delegated event handler onto the links in the page. You just have to make sure the handler is bound to links that may load a "new page".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top