0
我想解析一个多级json文件,创建一个模型,然后将该模型添加到骨干集合,但我似乎无法弄清楚如何将模型推送到集合。这应该是一个很容易解决的问题,我似乎无法弄清楚。在此先感谢您的帮助。以下是我的模型和收集代码:无法添加解析的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");
}
}
});
是什么'data.result.performers'样子?你觉得'this'在'_.each'回调中呢?永远不要修改集合的“模型”属性,您将使集合处于不一致状态,使用集合的方法来添加新模型。 –
对于mu说的同样,但也不是'parse'需要工作的方式是将数据结构作为参数并返回不同的结构作为返回值。它根本不应该使用'this'。为了修正你的'parse'代码,我们需要看到'data.result.performers'数据的一个样本,因为你的代码只是把它当作一个对象,而把它当作一个对象数组来对待。 –
明白了,我刚刚使用了var这个技巧,并解决了这个问题。我试图推动模型,因为正常this.push不工作,现在我知道为什么。谢谢! –