Canceling baseline routing due to unsaved form / model data

I have the following code. It creates a form with a simple text box.

<div class="nav-bar"> <a href="#home">Home</a> <a href="#showform">Click here for the form</a> </div> <div id="theform"> <form> <input type="text" name="data" id="data" /> <input type="submit"> </form> </div> 

After the user enters some data, he clicks on the home link. The highway starts navigation and calls the function for the house.

 var AppRouter = Backbone.Router.extend({ routes: { "home": "home", "showform": "showtheform", }, home: function() { if (current_view) { cuttent_view.remove(); } current_view = new View_Home(); }, showtheform: function() { // Code to show the form } }); 

After the handler, the form disappears, and unsaved changes remain unsaved (but cannot be saved later). Returning false in the router function does not affect anything, the URL changes anyway. How can I: a) prevent the URL from changing, and b) ask the user if he wants to save the unsaved changes?

+4
source share
1 answer

You can bind a handler in the view and execute your logic before starting the router. The advantage would be better than encapsulation, since validation is a problem for the view / model, not the router

 events: { "click a": "validateSave" }, validateSave: function(){ // check if we prompted to save already // if not return false and show a message; } // you can intercept other navigation events by guarding your routes like so. ... someRoute: function() { if(this.savePrompt() { return; } // show a different view }, savePrompt: function() { if(!current_view.validateSave || !current_view.validateSave()) { return false; } if(this.history.length < 2) { return false; } // go back silently and replace last route in history this.navigate(this.history[this.history.length-2], {replace: true}); return true; } 
-2
source

All Articles