Search code examples
javascriptjsonbackbone.js

Construct models from a Collection fetch in Backbone.js


I am using Backbone to retrieve data over a REST API. My code is as follows:

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

var PlayersCollection = Backbone.Collection.extend({
    url: "http://api.football-data.org/v1/teams/81/players",
    model: PlayerModel
});

var catalons = new PlayersCollection();
catalons.fetch();

This is the JSON output I receive if I do a GET request in POSTMAN

 {
  "_links": {
    "self": {
      "href": "http://api.football-data.org/v1/teams/81/players"
    },
    "team": {
      "href": "http://api.football-data.org/v1/teams/81"
    }
  },
  "count": 24,
  "players": [
    {
      "name": "Marc-André ter Stegen",
      "position": "Keeper",
      "jerseyNumber": 1,
      "dateOfBirth": "1992-04-30",
      "nationality": "Germany",
      "contractUntil": "2019-06-30",
      "marketValue": "15,000,000 €"
    },
    {
      "name": "Claudio Bravo",
      "position": "Keeper",
      "jerseyNumber": 13,
      "dateOfBirth": "1983-04-13",
      "nationality": "Chile",
      "contractUntil": "2018-06-30",
      "marketValue": "15,000,000 €"
    }
 ]
}

I am successfully able to receive data using fetch, the thing which I am unable to figure out is how do I parse the fetched data so that my collection catalons will contain nothing but only the players? i.e. similar to if I had set it up this way:

var catalons = new PlayersCollection(playerModelArray); 

Solution

  • You can do this using Backbone's Collection parse method. You simply need to add a parse method to your PlayersCollection prototype definition:

    var PlayersCollection = Backbone.Collection.extend({
        url: "http://api.football-data.org/v1/teams/81/players",
        model: PlayerModel,
        parse: function (response) {
            return response.players;
        }
    });