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

浪尽此生 提交于 2019-12-04 00:17:51
Loamhoof

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!