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

pay*_*ike 4 fetch node.js backbone.js

我知道骨干文档说 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();
Run Code Online (Sandbox Code Playgroud)

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

知道如何做到这一点?

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

ggo*_*zad 13

让我们从头开始:

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

});
Run Code Online (Sandbox Code Playgroud)

我会避免进入内部initialize.创建appCollection的实例不应该需要获取.所以使用:

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

然后,

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();
Run Code Online (Sandbox Code Playgroud)

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