Reputation: 51
I begin with Backbone and I would like to implement a simple application in order to manage users and products objects. The page layout is always the same : the header (top page), the menu (left column) and the content (right column) but the header and menu contents depend on the current module (user or product).
I search the proper way to manage my page layout. Actually, I manage the header and menu in each method of my Backbone.Router but I think that is not the best solution.
var appRouter = Backbone.Router.extend({
routes: {
"users": "listUser",
"users/new": "newUser",
"users/:id": "showUser",
"products": "listProduct",
"products/new": "newProduct",
"products/:id": "showProduct"
},
listUser: function() {
if (this.userHeaderView == null) {
var header= new UserHeaderView();
header.render();
this.userHeaderView = header;
}
if (this.userMenuView == null) {
var menu= new UserMenuView ();
menu.render();
this.userMenuView = menu;
}
this.contentView = new UserListView().render();
}
// ...
newProduct: function() {
if (this.productHeaderView == null) {
var header= new ProductHeaderView();
header.render();
this.productHeaderView = header;
}
if (this.productMenuView == null) {
var menu= new ProductMenuView();
menu.render();
this.productMenuView = menu;
}
this.contentView = new NewProductView().render();
}
// ...
});
Upvotes: 0
Views: 1138
Reputation: 72868
A router shouldn't be used to manage the application initialization. You should be creating an application object that manages the initialization process, sets up the headers and menus that you always need, etc. (Note that Backbone doesn't include an object such as this. It's up to you to create this object).
The router should only know what it absolutely needs to know, in order to get the application back to the state being requested.
I've written a few articles on this, and though my articles do reference my Backbone.Marionette framework, the principles of what I'm saying apply to standard Backbone use as well:
http://lostechies.com/derickbailey/2012/02/06/3-stages-of-a-backbone-applications-startup/
http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
http://lostechies.com/derickbailey/2011/08/30/dont-limit-your-backbone-apps-to-backbone-constructs/
I realize that I'm suggesting you read far more information than is probably necessary to directly answer you question. The combination of these articles, though, should inform you of a number of different ideas and perspectives that will help shape your use of Backbone so that you can avoid some of the common mistakes regarding routers, managing layout, closing views, etc.
Upvotes: 4