Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone JS parse json attribute to a collection's model

I'm having trouble parsing a json to a model.

Here is the JSON:

[
{
    "name": "Douglas Crockford",
    "email": "[email protected]",
    "_id": "50f5f5d4014e045f000002",
    "__v": 0,
    "items": [
        {
            "cena1": "Cena1",
            "cena2": "Cena2",
            "cena3": Cena3,
            "cena4": "Cena4",
            "cena5": "Cena5",
            "cena6": Cena6,
            "_id": "50ee3e782a3d30fe020001"
        }
    ]
}

]

And i need a model to have the 'items' attributes like this:

cena = new Model({ 
           cena1: "Cena1", 
           cena2: "Cena2",
           ... 
});

What I've tried:

var cenaCollection = new Backbone.Collection.extend({
   model: Cenas,
   url: '/orders',

   parse: function (response) {
      return this.model = response.items;
   }

});

then I create new instance of the collection and fetch, but i get "response.items" always "undefined" :|

Thanks in advance!

like image 974
asirgado Avatar asked Jan 16 '13 03:01

asirgado


1 Answers

The parse function should return the attributes hash to be set on the model (see the documentation here). So you'll need simply:

parse: function (response) {
   return response[0].items;
}
like image 102
McGarnagle Avatar answered Oct 26 '22 23:10

McGarnagle