I have a REST URL, say
/users/<user_id>/entities
which returns 2 objects within it:
{
"players":
{
"test_player2":
{
"_id": "test_player2",
"user": "f07590567f3d3570b4f35b4fd79f18b3"
},
"test_playerX":
{
"_id": "test_player2",
"user": "f07590567f3d3570b4f35b4fd79f18b3"
}
},
"games":
{
"game1" :{},
"game2" :{},
}
}
How do I design my Backbone Objects to use this data?
Requirement:
I want two different Backbone objects: Player, and Game, which should be populated via the same url (mentioned above).
PS: Is it even a correct practice to design this kind of REST URL?
No, it’s not a correct practice. In REST, a single URL is supposed to represent a single resource. Therefore, your
/users/<user_id>/entitiesURL should be/users/<user_id>/playersand only return a list of players, and/users/<user_id>/gamesand only return a list of games.However, there may be a time when you have no control over what the API returns. Generally, this is the case for nested objects (you may be able to do it with what you have, but ideally, you’ll want to change your API):
In which case, you would use the model’s
parsefunction, with something like:By overriding
parseand using{parse:true}, you can build out your models pretty much indefinitely. It’s not necessarily ideal to do it that way (the idea is that each collection is responsible for its own models), but it works for those cases when you get compound objects and can’t change what the API returns.