基本上,我正在尝试将get请求发送到我的节点服务器,以便我可以返回博客文章来创建链接。我做一个 collection.fetch, ,成功完成了GET请求(节点服务器日志正在发送正确的对象)。该模型成功解析了正确的数据,但是当我尝试使用该集合时,它说它是空的。这是代码:

var mdm = mdm || {};

// MODEL
mdm.Post = Backbone.Model.extend({
        parse: function( response ) {
        response.id = response._id;
        console.log(response); // logs the two documents
        return response;
    }
});

// COLLECTION
mdm.Posts = Backbone.Collection.extend({
    model: mdm.Post,
    url: '/api/posts'
});

// MODEL VIEW
mdm.LinkView = Backbone.View.extend({
    template: _.template( $('#link_template').html() ),

    render: function() {
        this.$el.html( this.template( this.model.toJSON() ));
        return this;
    }
});

// COLLECTION VIEW
mdm.LinksView = Backbone.View.extend({
    el: '#link_list',

    initialize: function() {
        this.collection = new mdm.Posts();
        this.collection.fetch({reset: true});
                // makes the request properly, but collection is empty
        this.render();
                // never gets called because the collection is empty
        console.log(this.collection.length); 
                // logs a length of 0
    },

    render: function() {
        // renders collection
    }
});

$(function() {
    new mdm.LinksView();
});

数据正在发送并在模型中解析,因此我不确定该集合最终是空的。任何帮助将不胜感激。

有帮助吗?

解决方案

您看不到模型的最大原因是因为渲染正在异步之前发生 fetch 已经完成。

下面的事情会更好:

mdm.LinksView = Backbone.View.extend({
    el: '#link_list',

initialize: function() {
    this.collection = new mdm.Posts();
    this.listenTo(this.collection, 'reset', this.render);
    this.collection.fetch({reset: true});
}

以上代码为侦听器设置了 reset 事件 collection 并执行 render 发生这种情况时的功能。

另外,你可以经过 successerror 处理者进入 fetch 并手动调用渲染函数。

this.collection.fetch({
    success: _.bind(function() { 
        this.render(); }, this)
});

希望这可以帮助!

其他提示

根据 @fbynite的评论,问题与 fetch 异步。我对收集视图进行了以下更改,它解决了问题:

initialize: function() {
    var self = this;
    this.collection = new mdm.Posts();
    this.collection.fetch({reset: true,
        success: function() {
            self.render();
            console.log(self.collection.length);
        }
    });
},

该代码是骨干教程的修改,因此其他用户可能会遇到类似的问题。 http://addyosmani.github.io/backbone-fundamentals/#exercise-2-book-library---your-first-restful-backbone.js-app

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top