我正在使用Backbone通过REST API检索数据。我的代码如下:
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();
如果我在POSTMAN中执行GET
请求,这是我收到的JSON输出
{
"_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 €"
}
]
}
我成功地能够使用fetch
接收数据,我无法弄清楚的是如何解析所获取的数据,以便我的集合catalons
只包含玩家?也就是说,如果我这样设置的话:
var catalons = new PlayersCollection(playerModelArray);
答案 0 :(得分:3)
您可以使用Backbone's Collection parse方法执行此操作。您只需要在PlayersCollection
原型定义中添加一个解析方法:
var PlayersCollection = Backbone.Collection.extend({
url: "http://api.football-data.org/v1/teams/81/players",
model: PlayerModel,
parse: function (response) {
return response.players;
}
});