1
votes

how can I rewrite the Backbone Collection fetch() function to get a specific part in my JSON?

The json I get looks like this:

{
   "success":true,
    "data":[
      {
         "id":1,
         "title":"asdf",
         "link":"http://www.xx.cc/image/asdf/",
         "date":1439993443000
      },
      {
         "id":2,
         "title":"qwer",
         "link":"http://www.xx.cc/image/qwer/",
         "date":1439993091000
      }
   ]
}

And my simple Backbone Script:

var myCollection = Backbone.Collection.extend({
    url: 'url.to/my/rest/'
});

myCollection.fetch();
console.log(myCollection);

the Problem here is, that the collection I get got a length of 1 with 1 model in in it. When I log that collection and open "n -> models -> 0 -> attributes -> data" I find all my objects within the JSON data array.

But I need the objects of tha "data"-array as models in my collection. So Far I found no solution to this problem so may someone got the right idea for me?

1

1 Answers

1
votes

Supply your collection description object with a parse function, as described in the docs:

var myCollection = Backbone.Collection.extend({
    url: 'url.to/my/rest/',
    parse: function(data) {
      return data.data;
    }
});

This method extracts the relevant part from the server's response and fill a collection based on this part.