Structure of Backbone Models and Collections based on JSON

38 Views Asked by At

I have this web app that tracks daily nutrients consumption through foods and presents them in a neat timeline.

I am new to Backbone and I am trying to structure my models and collections. How can I model the following JSON into Backbone Models/Collections?

Should it be a foods collection inside a day model?

{
      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'
            }
          ]
        }
      ]
}
1

There are 1 best solutions below

0
Przemek eS On

If you have JSON you can create collection and model

Creating model

var myModel = Backbone.Model.extend({});

Creating collection

var myCollection = Backbone.Collection.extend({
  model: myModel
});

var ourCollection = new myCollection(yourJSON);

In your example, I will create 2 collections (1 nested in model) CollectionOfDays -> ModelOfDay -> CollectionOfFoods (inside the model)

var randomDay = Backbone.Model.extend({});
var randomDayCollection = Backbone.Collection.extend({
  model: randomDay
});

var collection = new randomDayCollection(yourJSON);

model in collection have attributes:

date: '1/1/2011',
totalCalories: 1000,
totalCarbs: 100,
totalProtein: 60,
totalFats: 30,
foods: [Array] -food consumed in day

After that, you can create other model to one Food and Foods collection and overwrite your foods.