Backbone.js集合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;  
    }
});

调用提取:

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中?

响应必须是一个数组。数组中的每个项都将转换为一个模型。你的回答是一个对象。

更新您的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;
        });
    }
});

相关内容

  • 没有找到相关文章

最新更新