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 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.