无法将已解析的JSON添加到主干集合

时间:2013-10-09 19:15:16

标签: javascript backbone.js

我正在尝试解析多级json文件,创建模型然后将该模型添加到主干集合中,但我似乎无法弄清楚如何将模型推送到集合中。这应该是一个非常容易解决的问题,我似乎无法弄明白。在此先感谢您的帮助。下面是我的模型和集合代码:

var Performer = Backbone.Model.extend({

defaults: {
    name: null,
    top5 : [],
    bottom5 : []
},
initialize: function(){
    console.log("==> NEW Performer");

    // you can add event handlers here...


 }
});

var Performers = Backbone.Collection.extend({

url:'../json_samples/performers.json',
model:Performer,
parse : function(data) {
    // 'data' contains the raw JSON object
    console.log("performer collection - "+data.response.success);

    if(data.response.success)
    {
        _.each(data.result.performers, function(item,key,list){
            console.log("running for "+key);
            var tmpObject = {};
            tmpObject.name = key;
            tmpObject.top5 = item.top5;
            tmpObject.bottom5 = item.bottom5;
            var tmpModel = new Performer(tmpObject);
            this.models.push(tmpModel);
        });

    }
    else
    {
        console.log("Failed to load performers");
    }
}

});

1 个答案:

答案 0 :(得分:1)

正如在对您的问题的评论中所说,parse()并非打算以这种方式使用。如果data.results.performersArray,那么您只需返回它即可。在您的情况下,代码会略有不同。

var Performers = Backbone.Collection.extend({
    ...
    parse: function(resp, options) {
        return _.map(resp.result.performers, function(item, key) {
            return _.extend(item, {name: key});
        });
    }
    ...
});

在建议方面,如果您有机会更改API服务器端,您可能最好将对象集合视为数组而不是对象。即使有时通过某个ad-hoc键访问对象也很方便,但数据确实是一个数组。

当你需要使用像下划线IndexBy

这样的函数的名字时,你将能够转换它。
相关问题