Backbone - Collection fetch返回undefined?

时间:2012-09-07 08:21:19

标签: backbone.js

我有一个使用骨干的应用程序,但每当我为集合调用fetch()方法时,它返回undefined:

// App

(function () {

    window.app = {};
    app.collections = {};
    app.models = {};
    app.views = {};

    $(function () {
        app.collections.complaintTypes = new app.collections.ComplaintTypesCollection();
        app.views.complaintTypesView = new app.views.ComplaintTypesView({ collection: app.collections.complaintTypes });
    });

})();

// Collections

(function (collections, model) {
    collections.ComplaintTypesCollection = Backbone.Collection.extend({
        initialize: function () {
            this.fetch();
        },
        model: model,
        url: '/api/ComplaintTypes'
    });
})(app.collections, app.models.ComplaintType);

// Models

(function (models) {
    models.ComplaintType = Backbone.Model.extend({
        idAttribute: 'ComplaintTypeId'
    });
})(app.models);


// Views

(function (views) {
    views.ComplaintTypesView = Backbone.View.extend({
        initialize: function () {
            this.collection.on('reset', this.render, this);
        },
        render: function () {
            console.log(this.collection);
        }
    });
})(app.views);

但这不会返回什么?如果我使用fiddler并转到我的URL:/ api / ComplaintTypes我会检索数据,所以我不确定我在这里做错了什么?

3 个答案:

答案 0 :(得分:3)

删除集合文件中的“model”行对我有用。

答案 1 :(得分:1)

获取是异步的。如果需要获得结果,则需要传递“成功”处理程序,即:

function myHandler(models) {

}
...
this.fetch({success: myHandler});

答案 2 :(得分:1)

我认为问题是你在尚未提取集合时创建视图(因为JS的异步行为)。试试这个:

$(function () {
    app.collections.complaintTypes = new app.collections.ComplaintTypesCollection();
    app.collections.complaintTypes.fetch({success:function(){
        app.views.complaintTypesView = new app.views.ComplaintTypesView({ collection: app.collections.complaintTypes });
    }});      
});

并从您的收藏中删除初始化功能。