Prevent navigating to another view if contents are unsaved

前端 未结 6 1612
无人共我
无人共我 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 21:01

    I was getting multiple calls to loadUrl per reroute using Dénes's solution, so I decided to try this method, which worked for me.

    /**
     * Monkey patches Backbone to prevent a reroute under certain conditions.
     *
     * Solution inspired by: https://stackoverflow.com/a/24535463/317135
     *
     * @param Backbone {Backbone}
     *   Backbone 1.0.0 reference
     * @param disallowRouting {function(): boolean}
     *   Function returning `true` when routing should be disallowed.
     */
    export default function permitRouteWhen(Backbone, permitRouting) {
      if (Backbone.VERSION !== '1.0.0') {
        console.error(
          `WARNING: Expected to be hacking Backbone version 1.0.0, but got
          ${Backbone.VERSION} - this could fail.`
        );
      }
    
      const { checkUrl } = Backbone.history;
    
      Backbone.history.checkUrl = function(event) {
        if (!permitRouting()) {
          event.preventDefault();
          return;
        }
        return checkUrl.apply(this, arguments);
      }
    }
    

    Use it like this:

    import permitRouteWhen from './backbone-permit-route-hack';
    permitRouteWhen(window.Backbone, () => confirm('you wanna route?'));
    

提交回复
热议问题