Backbone.js集合提取未将响应对象设置为模型

时间:2015-06-21 20:19:54

标签: backbone.js collections fetch

当获取一个集合时,我的api响应有10个对象,但是生成的Backbone集合只有1个模型,其中一个属性数组包含10个响应对象....换句话说,fetch不创建模型我的回答中的对象......我不知道为什么。

模型定义:

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

    }
});

收藏定义:

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;  
    }
});

调用fetch:

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(myCollection)将

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?  

如何更改提取以将这些对象添加为myCollection中的单个模型?

1 个答案:

答案 0 :(得分:1)

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

更新你的parse方法,将值(作为一个数组)从响应中拉出到一个数组中,然后就可以了。

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;
        });
    }
});
相关问题