在页面加载时骨干提取集合

我知道backbone文档说fetch不应该被用来在页面加载时填充集合 ,而且我会弄清楚为什么:

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(); 

homeview.render函数实际上在获取集合之前被调用,所以当我删除alert(1); 我的应用程序不会得到渲染,我得到一些错误说“appname”(模板)是未定义的。

任何想法如何做到这一点?

取的方法来真的很方便,我不介意等待几秒钟,其实我打算显示一个进度条,表明该网页正在初始化,因为我有很多其他的东西要下载,所以有可能使用获取和当收集实际上提取,然后代码继续运行?

让我们从头开始:

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

我会避免进入initialize 。 创build一个appCollection的实例不应该需要抓取。 所以使用:

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

然后,

 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(); 

这允许您呈现您的homeView,并且当集合被提取时,它将渲染它的模型。 如果你不明白p.done是做什么的,可以看看jQuery的Deferred 。 简而言之,ajax请求返回一个承诺。 当promise被实现(即你的集合被提取)时,延迟的火焰和你在.done()指定的任何函数都会被执行。 使用我console.log的点来反馈进度。