Question

I am using a collection to fetch data from an API to place this into a model. I do receive all data from the API, however the data is returned in an object and I only need a part of this object.

Let me clarify this with an example of the returned JSON:

{
    "all-users":
         [
              {"username":"poekoe","lastsyncdate":"1376496898"},
              {"username":"plaap","lastsyncdate":"1376494547"}
         ],
     "total-users": "10",
     "selected": 2
}

This is the JSON returned, however I only want need the 'all-users' array to be placed in my model.

At this point I am fetching data like this:

 var userCollection = new UserCollection;
 userCollection.fetch({
     data: {
         "search": "p",
         "session: login.session
     }
 });

What can I do here to only use the 'all-users' array to be placed in the model? Is there something in the Fetch what I can do? or should I alter the Model to only use the all-users array?

Thanks in advance!

Was it helpful?

Solution

You can override the parse method of the collection:

var UserCollection = new Backbone.Collection.extend({
  parse: function(data){
    return data["all-users"];
  }
});

So your Collection will only consist of what the parse method returns, in this case the all-users array from your response json.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top