How to place a collection within a model in Backbone.js?

Charles picture Charles · Apr 14, 2013 · Viewed 11.6k times · Source

I would like some insight on how one would add structure a collection within a model. My simple app has teams (so a team model and collection of teams) and each team has a bunch of players(player model and player collections). So a visual structure of it is like so:

Team A
   - Player 1
   - Player 2
   - Player 3
Team B
   - Player 1
   - Player 2

and so on...

How would one structure such a backbone app? Here is how I am planning it so far: 1) I would have a Team Collection, that would hold multiple teams whose model property corresponds to the TeamModel. 2) A Player Collection, that would hold all multiple players and model property corresponds to the PlayerModel.

Now I am confused as to how I would have the Team Collection and Model, correspond with the Player Collection and Model. I.e. according to my design, a third relationship would be that each team would have a collection of players. However I am unsure of how to implement that.

Answer

Loamhoof picture Loamhoof · Apr 14, 2013

"Now I am confused as to how I would have the Team Collection and Model, correspond with the Player Collection and Model. I.e. according to my design, a third relationship would be that each team would have a collection of players."

Simply add an attribute to your Team Model that'd be a collection of players.

var Team = Backbone.Model.extend({
  initialize: function() {
    // assuming Players a collection of players
    this.set('players', new Players());
  }
});

Now, populating the data is another problem which has a lot of solutions. But doing things that way gives you a strong structure.