我从collection.fetch()
调用返回一个带有多个嵌套对象的对象。有没有办法解析这些子对象并将它们作为单独的模型传递给集合?
这是我要回来的数据的一个例子。当从服务器获取时,我想将它作为3个模型传递给集合。
这是我正在努力的小提琴,但我不确定最好的解决方法:http://jsfiddle.net/L8ov7oo5/
来自服务器的数据:
{
"slides": {
"date": "August 21, 2014",
"Author": "Luke Skywalker",
"slide1": {
"content": {
"headline": "headline 1",
"desc": "description for slide 1",
"image": [
{
"url": "http://placekitten.com/100/100",
"type": "thumbnail",
"alt": "imageofakitten"
}
]
}
},
"slide2": {
"content": {
"headline": "headline2",
"desc": "descriptionforslide2",
"image": [
{
"url": "http: //placekitten.com/125/125",
"type": "thumbnail",
"alt": "imageofakitten"
}
]
}
},
"slide3": {
"content": {
"headline": "headline3",
"desc": "descriptionforslide3",
"image": [
{
"url": "http: //placekitten.com/150/150",
"type": "thumbnail",
"alt": "imageofakitten"
}
]
}
}
}
}
我希望传递给集合的模型示例:
{
"slide1": {
"content": {
"headline": "headline 1",
"desc": "description for slide 1",
"image": [
{
"url": "http://placekitten.com/100/100",
"type": "thumbnail",
"alt": "imageofakitten"
}
]
}
}
}
这是我的代码,但是当我记录collection.fetch()
的结果时,我在集合中看不到3个模型。
var MyModel = Backbone.Model.extend({});
var MyCollection = Backbone.Collection.extend({
model: MyModel,
url: 'https://api.mongolab.com/api/1/databases/parse-test/collections/parse-test-collection?apiKey=x5akja343lqkja',
parse: function (response) {
console.log('response', response);
for (var prop in response[0].slides) {
if ( response[0].slides.hasOwnProperty(prop) ) {
// Try to add an object as a 'model' to the 'collection'
this.add( response[0].slides[prop] );
}
}
return response;
}
});
var myCollection = new MyCollection();
myCollection.fetch().done(function () {
// Expecting to see 3 models in this collection but I am not.
console.log(myCollection);
});
答案 0 :(得分:3)
只需删除属性日期和作者并返回幻灯片
即可 parse: function (response) {
//console.log('response', response[0]['slides']);
delete response[0]['slides'].date;
delete response[0]['slides'].Author;
var temp = [];
$.each( response[0]['slides'], function(index, val) {
temp.push(val);
});
return temp;
}
答案 1 :(得分:2)
您的集合的解析调用应该返回一个数组。在for-in循环中,将所需的每个对象添加到数组中,并在完成后从解析中返回数组。
var obj = response[0].slides,
returnList = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && prop !== 'date' && prop !== 'Author') {
returnList.push(obj[prop]);
}
}
return returnList;
这里有jsfiddle来演示。
编辑:这是另一个jsfiddle演示使用_.map()而不是for-in循环。
var obj = response[0].slides;
delete obj.date;
delete obj.Author;
return _.map(obj, function (value, key) {
return obj[key];
});