Prevent navigating to another view if contents are unsaved

前端 未结 6 1611
无人共我
无人共我 2021-02-05 20:24

We have a backbone.js app that displays a number of forms to the user. What we want is very simple: if the user goes to another page without saving the filled-in form, we want t

6条回答
  •  逝去的感伤
    2021-02-05 20:49

    I think you could hack Backbone.history.loadUrl ( http://documentcloud.github.com/backbone/docs/backbone.html#section-137 ). I did a quick test, this code does a check every time you change pages. You'll want to add code to activate the check only when there is actually a reason for it.

    var goingBack = false;
    function doCheck() {
      // TODO: add code that checks the app state that we have unsaved data
      return goingBack || window.confirm("Are you sure you want to change pages?");
    }
    
    var oldLoad = Backbone.History.prototype.loadUrl;
    Backbone.History.prototype.loadUrl = function() {
      if(doCheck()) {
        return oldLoad.apply(this, arguments);
      } else {
        // change hash back
        goingBack = true;
        history.back();
        goingBack = false;
        return true;
      }
    }
    

    You'll have to handle window.onbeforeunload as well, because the user might still leave the page entirely.

提交回复
热议问题