Assembling the base grid when loading the page

I know that the base document says that sampling should not be used to populate collections when the page loads , and I understand why:

var appCollection = Backbone.Collection.extend({ model:appModel, url:'api/app', initialize:function(){ this.fetch(); }, }); var homeView = Backbone.View.extend({ el:'#content', initialize:function(){ this.collection = new appCollection(appModel) this.render() }, render: function () { var that = this; alert(1); _.each(this.collection.models, function (item) { that.renderApp(item); }, this); }, renderApp: function (item) { var appview = new appView({ model: item }); this.$el.append(appview.render().el); } }) var home = new homeView(); 

the homeview.render function is actually called before the collection is collected, so when I remove the warning (1); my application will not be displayed and I get an error: "appname" (template) is undefined.

any idea how to do this?

the fetch method comes in very conveniently, and I don't mind waiting a few seconds, in fact I was going to show a progress bar indicating that the page is initializing because I have a lot of other things to load, so you can use fetch when the collection is actually loaded , then the code continues to work.

+4
source share
1 answer

Take this from the start:

 var appCollection = Backbone.Collection.extend({ model:appModel, url:'api/app', initialize:function(){ this.fetch(); }, }); 

I would not choose inside initialize . Creating an instance of appCollection should not require fetching. Therefore use:

 var appCollection = Backbone.Collection.extend({ model:appModel, url:'api/app', }); 

Then

 var homeView = Backbone.View.extend({ el:'#content', initialize:function(){ this.collection = new appCollection(appModel) this.render() }, render: function () { var that = this, p; console.log('fetching...'); p = this.collection.fetch(); p.done(function () { console.log('fetched!'); _.each(that.collection.models, function (item) { that.renderApp(item); }, that); }); }, renderApp: function (item) { var appview = new appView({ model: item }); this.$el.append(appview.render().el); } }) var home = new homeView(); 

This allows you to display your homeView, and when the collection is retrieved, it will display its models. If you don't understand what p.done doing, see jQuery Postponed . In short, the ajax request returns a promise. When a promise is fulfilled (i.e. your assembly), deferred lights and any function specified in .done() will be executed. Use the points where I console.log to give feedback on the progress.

+13
source

All Articles