gpt4 book ai didi

javascript - 主干 - 将对象解析为模型以供收集

转载 作者:行者123 更新时间:2023-11-30 08:42:02 27 4
gpt4 key购买 nike

我从 collection.fetch() 调用中得到一个包含多个嵌套对象的对象。有没有办法解析这些子对象并将它们作为单独的模型传递到集合中?

这是我要返回的数据的示例。从服务器获取时,我想将它作为 3 个模型传递到集合中。

这是我正在尝试的 fiddle ,但我不确定最好的方法: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);
});

最佳答案

只需删除属性日期和作者并返回幻灯片

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

DEMO

关于javascript - 主干 - 将对象解析为模型以供收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25438614/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com