I have been working on a solution for this issue for some time now, and I have finally found a resolution. After finding inspiration from this example, I decided to implement my own approach.
The concept involves overriding the navigate
method and utilizing jQuery
deferred
objects to navigate at the appropriate moment. In my scenario, when a user attempts to navigate away from my view with unsaved changes, a dialog is displayed asking them to:
1) Save the changes before navigating
2) Proceed without saving changes
3) Cancel navigation and stay on the current page
Below is the code snippet that showcases my implementation of the Router
's navigate method:
navigate: function(fragment, trigger) {
var answer,
_this = this;
answer = $.Deferred();
answer.promise().then(function() {
return Backbone.Router.prototype.navigate(fragment, trigger);
});
if(fragment !== undefined){
var splitRoute = fragment.split('/');
app.currentPatronSection = splitRoute[splitRoute.length - 1];
}
if (app.recordChanged) {
this.showConfirm(function(ans){
// Clear out the currentView
app.currentView = undefined;
answer.resolve();
}, function(){
});
return answer.promise();
} else {
return answer.resolve();
}
return Backbone.Router.prototype.navigate(fragment, trigger);
},
The showConfirm
method displays the dialog offering the three aforementioned options. Depending on the user's selection, I either save the form, resolve the answer to proceed with navigation, etc.