[英]create a complex collection in backbonejs
In short i want to make a backbone deep collection of other collections and models 总之,我想做一个骨干深度收集其他集合和模型
the structure is like this 结构是这样的
[{
mainCategory: "Something"
subCategories: [
{
category: "SomethgingElse",
labs: [
{
id: 1,
title: "Title",
description : "Lorem ipsum dolor sit amet"
availablelanguages: ["fr","en"]
},
{
id: 2,
title: "Another Title",
description : "Lorem ipsum dolor sit amet",
availablelanguages: ["fr","en"]
}]
},
{
category: "Testing",
labs: [
{
id: 1,
title: "ZZZZ",
description : "Lorem ipsum dolor sit amet"
availablelanguages: ["ar","en"]
},
{
id: 2,
title: "VVVVV",
description : "Lorem ipsum dolor sit amet",
availablelanguages: ["ar","en"]
}]
}
]
}]
i defined some collections and models like the following 我定义了一些集合和模型,如下所示
var Item = Backbone.Model.extend({
defaults: {
title : '',
description: '',
availableLangagues : []
}
});
var Items = Backbone.Collection.extend({
model: Item
});
var Category = Backbone.Model.extend({
defaults: {
categoryName: '',
labsList: new Items()
}
});
var Categories = Backbone.Collection.extend({
model: Category
});
var TopCategory = Backbone.Model.extend({
defaults: {
topCategory: "",
categories: new Categories()
}
});
var TopCategories = Backbone.Collection.extend({
model: TopCategory
});
My problem here i want to call fetch
on the TopicCategories
i want to populate everything , the fetch
will return a JSON
like passed in the example, but if i called fetch
on TopCategories
it will return the data but the array will be just normal JavaScript array not a backbone collection like i wanted in the defaults 我的问题在这里我想在
TopicCategories
上调用fetch
我想要填充所有东西, fetch
将返回一个像示例中传递的JSON
,但是如果我在TopCategories
上调用fetch
它将返回数据但是数组将只是普通的JavaScript数组不是我想要的默认骨干集合
What you want to do is utilize your parse()
function of your top model. 你想要做的是利用顶级模型的
parse()
函数。 In this modified, parse, what you do is tease out the different object/arrays from your response and transform them into the collections you desire. 在这个经过修改的解析中,您所做的是从响应中梳理出不同的对象/数组,并将它们转换为您想要的集合。 Example:
parse()
in the TopCategory model. 示例:TopCategory模型中的
parse()
。
parse: function(response) {
if (response.subCategories){
if (!this.subCategories) {
this.subCategories = new Categories(response.subCategories);
} else {
this.subCategories.reset(response.subCategories);
}
delete response.subCategories;
}
return response;
}
You'll do this pattern in the parse definition for each parent model that has some sort of backbone collection that you want to parse out. 您将在每个父模型的解析定义中执行此模式,该模型具有您要解析的某种主干集合。
This link might give you some more ideas as to how this all works. 这个链接可能会给你一些关于这一切如何运作的更多想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.