Checking unsaved changes when switching views in backbone.js

I am new to Javascript and backbone.js, so hopefully I missed something simple here. I am experimenting with some sample code that I found that should check for unsaved changes before allowing the user to go to another page. Here I created a JSfiddle:

http://jsfiddle.net/U43T5/4/

The code subscribes to the hashchange event as follows:

$(window).on("hashchange", router.hashChange);

And the function router.hashChangechecks the dirty flag to determine whether or not to allow navigation, for example:

hashChange: function (evt) {
    if (this.cancelNavigate) { // cancel out if just reverting the URL
        evt.stopImmediatePropagation();
        this.cancelNavigate = false;
        return;
    }
    if (this.view && this.view.dirty) {
        var dialog = confirm("You have unsaved changes. To stay on the page, press cancel. To discard changes and leave the page, press OK");
        if (dialog == true) return;
        else {
            evt.stopImmediatePropagation();
            this.cancelNavigate = true;
            window.location.href = evt.originalEvent.oldURL;
        }
    }
},

The problem is that the code does not work, because it this.viewis undefined, so the 2nd if block is never entered.

, - ( this.view.dirty true, ). , , .

+1
2

this , this Window, . undefined, . initialize, .

 initialize: function() {
        _.bindAll(this, 'loadView', 'hashChange');
    },

Check Fiddle

+1

, - .

Backbone:

    var ignore = false;

    Backbone.history.checkUrl = function() {

            if (ignore) {
                ignore = false;
                return;
            }

            app.dirtyModelHandler.confirm(this, function () {
                Backbone.History.prototype.checkUrl.call(Backbone.history);
            },
            function() {
                ignore = true;
                window.history.forward();

            });

    };

app.dirtyModelHandler.confirm - , (Ok, Cancel) .

0

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


All Articles