I think I don’t quite get the idea behind the proper usage of Backbone routers. Here’s what I’ve got:
I have some data that I fetch from the server when the page loads and then pack it into models and collections. The number of those models and collections is indefinite. I want to use the router to be able to render the certain collection’s view directly from the start.
The problem is: Backbone router starts up early, and since I ask it to access a certain view and trigger its render
action, it cannot do that, because those views are not yet created. That means I actually have to make my routes start up after the fetch is complete.
I don’t know if this is a proper way to do it, but the only idea I came up with is to:
- Wrap the routes definition and the
Backbone.history.start();
bit into a separate top-level-accesible function (i.e. prepare to call it manually later on). - Run that function as the
success
callback for my collections’sfetch()
- The number of those collections is unknown, also I have no way to find out when all of them have been fetched, and I don’t want to start the routes more than once. So I make use of
_.defer()
and_.once()
.
This works, but it sure looks very weird:
Routers:
window.startRoutes = _.once(function() {
var AccountPage = Backbone.Router.extend({
routes: {
'set/:id': 'renderSet',
},
renderSet: function(setId) {
/** … **/
// Call the rendering method on the respective CardView
CardsViews[setId].render();
}
});
var AccountPageRouter = new AccountPage;
Backbone.history.start();
});
Collection:
window.CardsCollection = Backbone.Collection.extend({
model: Card,
initialize: function(params) {
/** … **/
// Get the initial data
this.fetch({success: function() {
_.defer(startRoutes);
}});
},
});
So my question is… am I doing it right? Or is there a better way to do this (must be)?