I know there are great deal of tutorials/information about orgaising an application using Backbone.js out there. I am creating gradually one with the aid of the those tutorials. I seem to fail understanding the concept of routers. Well, I am aware that routers are starting point(and tells the state of an app) and it's better to avoid putting more logic there.
I have one router. My app would firstly load header, footer, and main part of the page. In main part, first, I should login the user. To load the login page, I would do something like this:
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 to show inbox, sentbox for example.
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 call here one of the router's method to show that in address bar. Why I am confusing is because it's said that usage of one router is better than more. If I do so, my AppRouter
will be more complicated. Another issue is if users type the address directly, I should load that page. I think it requires to put the logic inside the AppRouter.
Please tell me the right approach here. Thanks beforehand!
Check out Router.navigate() (http://documentcloud.github.com/backbone/#Router-navigate)
I normally save an instance variable of my Router inside my App 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 within my view, if I want to navigate to a new route, I call:
App.data.mainRouter.navigate('route2/param1');