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
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?'));