如何在Backbone.js中的模型中放置集合?
我想了解如何在模型中添加集合结构。我的简单应用程序有团队(团队模型和团队集合),每个团队有一组玩家(玩家模型和玩家集合)。它的视觉结构是这样的:如何在Backbone.js中的模型中放置集合?,backbone.js,backbone.js-collections,Backbone.js,Backbone.js Collections,我想了解如何在模型中添加集合结构。我的简单应用程序有团队(团队模型和团队集合),每个团队有一组玩家(玩家模型和玩家集合)。它的视觉结构是这样的: Team A - Player 1 - Player 2 - Player 3 Team B - Player 1 - Player 2 等等 如何构建这样一个主干应用程序?以下是我目前的计划: 1) 我将有一个团队集合,它将容纳多个团队,其模型属性对应于TeamModel。 2) 一个播放器集合,它将容纳所有多个播放器
Team A
- Player 1
- Player 2
- Player 3
Team B
- Player 1
- Player 2
等等
如何构建这样一个主干应用程序?以下是我目前的计划:
1) 我将有一个团队集合,它将容纳多个团队,其模型属性对应于TeamModel。
2) 一个播放器集合,它将容纳所有多个播放器,并且模型属性对应于PlayerModel
现在我很困惑,我该如何让团队集合和模型与玩家集合和模型相对应。也就是说,根据我的设计,第三种关系是每支球队都有一批球员。但是,我不确定如何实现这一点。您可以执行以下操作:
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'
});
然后,当您创建每个的实例并从服务器收集数据时,在填充所有集合后启动路由器。
应该是这样的。“现在我不知道如何让团队集合和模型与玩家集合和模型相对应。也就是说,根据我的设计,第三种关系是每个团队都有一个玩家集合。”
只需向您的团队模型添加一个属性,该属性将是一个玩家集合
var Team = Backbone.Model.extend({
initialize: function() {
// assuming Players a collection of players
this.set('players', new Players());
}
});
现在,填充数据是另一个有很多解决方案的问题。但这样做会给你一个强大的结构。@clockwork189顺便说一句,我没有精确化它,但你不能将它放在默认值中。否则,所有实例将共享同一个集合。