Backbone.js collection 获取未将响应 objects 设置为模型

Backbone.js collection fetch not setting response objects as models

获取 collection 时,我的 api 响应有 10 个 objects,但生成的 Backbone collection 只有 1 个带有属性数组的模型包含 10 个响应 objects...换句话说,获取不是在我的响应中从 objects 创建模型...我不知道为什么。

模型定义:

MyApp.Item = Backbone.Model.extend({
    initialize: function(){

    }
});

Collection定义:

MyApp.ItemCollection = Backbone.Collection.extend({
    model: MyApp.Item,
    url: '/api/v1/item/',
    parse : function(response){
        //api returns objects in the content attribute of response, need to override parse
        return response.content;  
    }
});

调用提取:

var myCollection = new MyApp.ItemCollection();

myCollection.fetch({
    traditional: true,
    data: {  //url params for api call
        u_id: currentUser.id,
        order: 'sort_date:desc',
        start: 0,
        num_items: 10,
        format:'json'}
    });

结果:

console.log(response.content);

4571221007823F95BAAFB2BDF81111XX: Object
0124207763051005AAF59694458EBFXX: Object
3324207755431003B589CEF237DBE1XX: Object
3470000061641005BFB5D9983156E0XX: Object
3515553061641005A02884677F5624XX: Object
3526033426761006AFEA9852B0DDB5XX: Object
21431252714010079E4D8413429DB0XX: Object
26570547220410068F60D1B07D2E08XX: Object
37557124663710079DDC81EE855981XX: Object
0152243312031007957B94F5073B69XX: Object

//api successfully returns an array of objects, with GUID as key

console.log(我的Collection);

r {length: 1, models: Array[1], _byId: Object}

//why only one model? why not 10?

console.log(myCollection.models[0].attributes);

4571221007823F95BAAFB2BDF81111XX: Object
0124207763051005AAF59694458EBFXX: Object
3324207755431003B589CEF237DBE1XX: Object
3470000061641005BFB5D9983156E0XX: Object
3515553061641005A02884677F5624XX: Object
3526033426761006AFEA9852B0DDB5XX: Object
21431252714010079E4D8413429DB0XX: Object
26570547220410068F60D1B07D2E08XX: Object
37557124663710079DDC81EE855981XX: Object
0152243312031007957B94F5073B69XX: Object
__proto__: Object

//there they are...but why?  

我如何更改提取以将这些 objects 作为单独的模型添加到我的 Collection 中?

响应必须是数组。数组中的每一项都变成了一个模型。您的回复是一个对象。

更新您的解析方法以将响应中的值(作为数组)提取到数组中,它会起作用。

MyApp.ItemCollection = Backbone.Collection.extend({
    model: MyApp.Item,
    url: '/api/v1/item/',
    parse : function(response){
        //api returns objects in the content attribute of response, need to override parse
        return _.map(response.content, function(model, id) {
            model.id = id;
            return model;
        });
    }
});