Call route inside a baseline view

I know that there are a lot of tutorials / information on organizing the application using Backbone.js. I create one gradually using these tutorials. I don't seem to understand the concept of routers. Well, I know that routers are the starting points (and report the status of the application), and it's better to avoid adding more logic there.

I have one router. My app first loaded the header, footer and body of the page. Basically, firstly, I have to log in to the user system. To load the login page, I would do the following:

var AppRouter = Backbone.Router.extend({ initialize : function() { var headerView = new HeaderView({el:$('#header')}); headerView.render; var footerView = new FooterView({el:$('#footer')}); footerView.render; var loginView = new LoginView({el:$('#login')}); loginView.render; }, routes : { "inbox" : "inbox", "sentbox : "sentbox" }, inbox : function() { // ... }, sentbox : function() { // ... } }); app = new AppRouter(); Backbone.history.start(); 

After successful login, the mail page will be loaded. MailView has some events for displaying incoming messages, for example, the sender.

  events: { "click .inbox": "showInbox", "click .sentbox": "showSentbox", }, showInbox : function() { // app.route() or app.inbox() - ? } 

At this point, I want the router to show ../#inbox and ../#sentbox respectively. I am wondering if I should name one of the router methods here to show this in the address bar. Why am I confusing because he said that using one router is better than more. If I do this, my AppRouter will be more complex. Another problem is that if the user types the address directly, I have to load this page. I think this requires the logic to be built into the AppRouter.

Please tell me the right approach here. Thanks in advance!

+6
source share
3 answers

Check Router.navigate () ( http://documentcloud.github.com/backbone/#Router-navigate )

I usually save the instance variable of my router inside the application object, e.g.

 var App = { Views: {}, Routers: {}, Models: {}, data: {} initialize: function() { this.data.mainRouter = new App.Routers.MainRouter(); } }; 

where App.MainRouter is defined as:

 App.Routers.MainRouter = Backbone.Router.extend({ routes: { 'route1' : 'route1handler', 'route2/:param' : 'route2handler' }, ... }); 

Then in my view, if I want to go to a new route, I call:

 App.data.mainRouter.navigate('route2/param1'); 
+12
source

You simply send the browser to the appropriate route via:

 location.href = "#/the_route_you_want"; 

The listener inside Backbone.history will capture the hashChange event, and the corresponding view will be displayed.

This can be done in a very simple way via HTML:

 <a href="#/the_route_you_want">The Route You Want</a> 

For further reading.

+7
source

If you also want to call the route function, set the trigger parameter to true:

 app.navigate("help/troubleshooting", {trigger: true}); 
+1
source

All Articles