【问题标题】:backbone fetch collection on page load页面加载时的主干获取集合
【发布时间】:2012-08-07 17:09:52
【问题描述】:

我知道主干文档说 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”(模板)是未定义的。

知道怎么做吗?

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

【问题讨论】:

  • 您将在 collection.fetch({success:fn,error:fn},{wait:true}) 内执行此操作 successFn 您将渲染集合
  • 将你的收藏绑定到重置事件。 collection.on("reset", this.reset, this)

标签: node.js backbone.js fetch


【解决方案1】:

让我们从头开始:

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

});

我会避免在initialize 中获取。创建 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's Deferred。简而言之,ajax 请求返回一个承诺。当 promise 完成时(即你的集合被获取),延迟触发和你在.done() 中指定的任何函数都会执行。 使用我console.log 的点来反馈进度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多