13

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.

Charles
  • 638
  • 2
  • 9
  • 23

2 Answers2

15

"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.

Paweł Obrok
  • 22,568
  • 8
  • 74
  • 70
Loamhoof
  • 8,293
  • 27
  • 30
  • 6
    @clockwork189 Btw, I haven't precised it but you can't put it in the *defaults*. Otherwise, all your instances will share the same collection. – Loamhoof Apr 15 '13 at 07:34
6

You could do something like:

App.Models.Player = Backbone.Model.extend({});

App.Collections.Players = Backbone.Collection.extend({
    model: App.Models.Player,
    url: 'players',
    getTeam: function(idTeam){
        var gf = _.filter( this.models, function(model){
    return (
        model.get('idTeam') == idTeam
    );
    });
        return gf;
    }
});

App.Models.Team = Backbone.Model.extend({
    players: players( this.get('id') ) // asuming that players is an App.Collections.Players instance.
});

App.Collections.Team = Backbone.Collection.extend({
    model: App.Models.Team,
    url: 'teams'
});

And then, when you create the instances of each and collect data from the server, start the router once all collections have been populated. It should work that way.

Pablo
  • 1,173
  • 4
  • 18
  • 46