Javascript 如何使用主干读取通过相同REST URL返回的两个不同对象?
比如说,我有一个REST URLJavascript 如何使用主干读取通过相同REST URL返回的两个不同对象?,javascript,ajax,backbone.js,Javascript,Ajax,Backbone.js,比如说,我有一个REST URL /users/<user_id>/entities 如何设计主干对象来使用这些数据 要求: 我想要两个不同的主干对象:Player和Game,它们应该通过相同的url(如上所述)填充 PS:设计这种RESTURL是正确的做法吗 设计这种RESTURL是正确的做法吗 不,这不是正确的做法。在REST中,单个URL应该表示单个资源。因此,您的/users//entitiesURL应该是/users//players,并且只返回玩家列表,/users//
/users/<user_id>/entities
如何设计主干对象来使用这些数据
要求:
我想要两个不同的主干对象:Player和Game,它们应该通过相同的url(如上所述)填充
PS:设计这种RESTURL是正确的做法吗
设计这种RESTURL是正确的做法吗
不,这不是正确的做法。在REST中,单个URL应该表示单个资源。因此,您的/users//entities
URL应该是/users//players
,并且只返回玩家列表,/users//games
并且只返回游戏列表
但是,有时您可能无法控制API返回的内容。通常情况下,嵌套对象就是这种情况(您可以使用现有的内容来完成,但理想情况下,您需要更改API):
在这种情况下,您将使用模型的parse
函数,类似于:
parse: function(response)
{
// Make sure "games" actually exists and is an array to make a collection from
if(_.isArray(response.games))
{
// Backbone will automatically make a collection of models from an array
// Use {parse: true} if you want the receiving collection to parse as if a fetch had been done
this.games = new GamesCollection(response.games,{parse: true});
}
}
通过重写
parse
并使用{parse:true}
,您可以无限期地构建模型。这样做并不一定理想(想法是每个集合负责自己的模型),但它适用于获得复合对象且无法更改API返回内容的情况。谢谢Shauna。答案似乎合乎逻辑。我会尽快试用的!
{
"players":
{
"id": 1,
"games":
{
"id": 1745,
"title": "Team Fortress 2"
}
}
}
parse: function(response)
{
// Make sure "games" actually exists and is an array to make a collection from
if(_.isArray(response.games))
{
// Backbone will automatically make a collection of models from an array
// Use {parse: true} if you want the receiving collection to parse as if a fetch had been done
this.games = new GamesCollection(response.games,{parse: true});
}
}