I'm in the midst of creating my first backbone app using Node/express and Mongodb. The app is an online food menu and ordering system that collects all the data from mongo on the first page load and pushes it into a Backbone collection. I'm using the initialize function in the Backbone Router to fetch() the data and put it into a collection. My problem is that the index Router is loading before the Initialize function has finished. I have confirmed that the initialize function runs correctly because I can access the collection in the browser console.
I may be going about this the wrong way but here is a simplified version of my router:
GDB.Router = Backbone.Router.extend ({
routes: {
'': 'index',
'drinks': 'drinks'
},
meals: {},
initialize: function() {
meals = new GDB.Collections.Meals
meals.fetch();
},
index: function() {
var mealsView = new GDB.Views.Meals ({collection: meals});
$('#GDBContainer').append(mealsView.render().el);
},
drinks: function() {
var drinksView = new GDB.Views.Meals ({collection: meals.byCategory('drinks')});
$('#GDBContainer').append(drinksView.render().el);
}
});
Most likely, the initialize function has finished before the index function is called, but your fetch is asynchronous so the collection is not finished loading when you try to render your mealsView.
GDB.Router = Backbone.Router.extend ({
routes: {
'': 'index',
'drinks': 'drinks'
},
initialize: function() {
this.meals = new GDB.Collections.Meals
// fetch returns a jquery promise
this.fetchingMeals = this.meals.fetch();
},
index: function() {
var self = this;
// maybe show loading spinner here
$('#GDBContainer').html('<div>Loading</div>');
this.fetchingMeals.done(function(){
// now this.meals is done fetching!
var mealsView = new GDB.Views.Meals ({collection: self.meals});
$('#GDBContainer').html(mealsView.render().el);
});
},
drinks: function() {
var self = this;
// maybe show loading spinner here
$('#GDBContainer').html('<div>Loading</div>');
this.fetchingMeals.done(function(){
var drinksView = new GDB.Views.Meals ({collection: self.meals.byCategory('drinks')});
$('#GDBContainer').html(drinksView.render().el);
});
}
});
You can use Paul's solution, or listen to collection's add/reset/whatever events in the view.
view.listenTo(model, 'reset', view.render);