Prevent user from moving with unsaved changes

I am currently using Backbone.Marionette to create a SPA, and in one view the user can navigate with unsaved changes. I can control some of these events, such as buttons and menu options in the view, that will distract the user, but some others will require you to manipulate either Backbone.Router or work directly with DOM events.

I already tried listening beforeunload(does not work, because the application is still loaded) and hashchange(does not work, since you can not stop the browser from navigating). These solutions ( 1 , 2 , 3 ) do not work in this case, Javascript is never unloaded.

Changing Backbone.Router seems like the best option, but because of how it is initialized, I don’t think it is possible to introduce this function, or at least I cannot find a way to do it. This solution , for example, does not work because it is hashchangenot canceled (you cannot call stopPropagation on it) and this other solution does not work because it is navigatenot defined on the Backbone.Router object.

Any suggestions?

+4
source share
1 answer

I managed to find a solution to this, although another job is required. For this solution, I assume that you are tracking when the view is dirty.

There are 4 main ways to exit a view;

  • Click on the link to view
  • "" " "
  • "/"

1.

. , , . , , historyBack. :

historyBack: function() {
    if (this.isDirty) {
         answer = confirm("There are unsaved changes.\n\nDo you wish to continue?")

        if (answer) {
            this.isDirty = false
            window.history.back()
        }
    }

    else {
        window.history.back()
    }
}

2.

, execute, navigate, .

, , . , , .

:

_.extend(Backbone.Router.prototype, {

    execute: function (callback, args, name) {
        if (Backbone.Router.isDirty) {
            answer = confirm "There are unsaved changes.\n\nDo you wish to continue?";

            if (!answer) {
                return false;
            }
        }

        Backbone.Router.isDirty = false
        if (callback) callback.apply(this, args) 
    }
}

3.

Javascript, , beforeunload (. ). , , , , :

onShow: function() {
    $(window).bind("beforeunload", function (e) {
        if (this.isDirty) {
             return "There are unsaved changes.";
        }
    }
}

onDestroy: function() {
    $(window).unbind("beforeunload");
}

4. /

, . / , 1 3, , , .

/ , : . , "" , , .

, , , .

0

Source: https://habr.com/ru/post/1615220/


All Articles