我有这个网络应用程序,通过食物跟踪每日营养素消耗,并在一个整洁的时间表中呈现。
我是Backbone的新手,我正在尝试构建我的模型和集合。如何将以下JSON建模为Backbone模型/集合?
它应该是 day 模型中的食物集合吗?
{
response: [
{ // a random day
date: '1/1/2011',
totalCalories: 1000,
totalCarbs: 100,
totalProtein: 60,
totalFats: 30,
foods: [
{ // a food consumed in this day
datetime: '1/1/2011 17:30',
calories: 500,
proteins: 30,
carbs: 50,
fats: 15,
img: 'link_to_img'
},
{
datetime: '1/1/2011 19:30',
calories: 500,
proteins: 30,
carbs: 50,
fats: 15,
img: 'link_to_img'
}
]
},
{ // another day
date: '3/1/2011',
totalCalories: 1000,
totalCarbs: 100,
totalProtein: 60,
totalFats: 30,
foods: [
{
datetime: '3/1/2011 17:30',
calories: 500,
proteins: 30,
carbs: 50,
fats: 15,
img: 'link_to_img'
},
{
datetime: '3/1/2011 19:30',
calories: 500,
proteins: 30,
carbs: 50,
fats: 15,
img: 'link_to_img'
}
]
}
]
}
答案 0 :(得分:0)
如果你有JSON,你可以创建集合和模型
var myModel = Backbone.Model.extend({});
var myCollection = Backbone.Collection.extend({
model: myModel
});
var ourCollection = new myCollection(yourJSON);
在您的示例中,我将创建2个集合(1个嵌套在模型中)
CollectionOfDays
- > ModelOfDay
- > CollectionOfFoods
(在模型中)
var randomDay = Backbone.Model.extend({});
var randomDayCollection = Backbone.Collection.extend({
model: randomDay
});
var collection = new randomDayCollection(yourJSON);
集合中的模型具有属性:
date: '1/1/2011',
totalCalories: 1000,
totalCarbs: 100,
totalProtein: 60,
totalFats: 30,
foods: [Array] -food consumed in day
之后,您可以为一个Food and Foods系列创建其他模型并覆盖您的食物。