使用backbone.js我设置了一个 appView
,可以很好地呈现内部的两个视图( teamView
和 {{1} ),应用视图可以访问 playerView
和 teams
两个集合,并像这样呈现两个集合。
players
现在这很明显,但结果是这样的。
this.teams.each(function(team) {
var teamView = new TeamView({ model: team }); // New instance of the team view
var teamHtml = teamView.render().el; //So I set the html as a list of teams
this.$el.append(teamHtml); // Append it
var teamPlayers = this.players.where({team_id: team.get('id')}) // Organize so that players matches his team id.
console.log(teamPlayers)
_.each(teamPlayers, function(player) { // Run a list of the associated players to team
var playerView = new PlayerView({ model: player }); // New instance of the player view
var playerHtml = playerView.render().el; //set the html as a list of players
this.$el.append(playerHtml); //append it
console.log(player.toJSON());
}, this);
}, this);
所以你可以看到,当我运行<ul>// The root of the app view
<div>// The root of the team view
<strong>Lakers</strong>
</div>
<li>Kobe Bryant</li>// The root of the player view
<li>Pau Gasol</li>// The root of the player view
<div>// The root of the team view
<strong>Heat</strong>
</div>
<li>LeBron James</li>// The root of the player view
<li>Dwayne Wade</li>// The root of the player view
</ul>
团队时,我将其设置为循环团队视图,然后根据它设置它来循环播放器视图,显然为什么结果看起来像这样。
我感到困惑的是如何在团队视图中设置玩家视图。当然我已经尝试在团队视图中循环玩家,但没有循环团队我很难运行_.each
在视图中思考它我可以访问var teamPlayers = this.players.where({team_id: team.get('id')}) // Organize so that players matches his team id.
替换this.model.get('id')
并使用它,但每次我提出一个想法它失败因为我错过了最小的细节,我最终浪费时间。所以我想我可以澄清这一点,得到一些学习并给出一些观点。
所以最后我想得到一个像这样的HTML结果。
team.get('id')
我觉得这是一个非常简单的问题,但我通过stackoverflow学习得最好。希望你们知道我的意思,HTML结果解释了这一切:)
谢谢!
完整代码: 以防万一
<ul>// The root of the app view
<div>// The root of the team view
<strong>Lakers</strong>// This isn't important just need it inside the view
<li>Kobe Bryant</li>// The root of the player view
<li>Pau Gasol</li>// The root of the player view
</div>
// You see the difference, the player view is now inside the team view and both are inside the app view.
<div>// The root of the team view
<strong>Heat</strong>// Again this isn't important just need it inside the view
<li>LeBron James</li>// The root of the player view
<li>Dwayne Wade</li>// The root of the player view
</div>
</ul>
答案 0 :(得分:1)
您似乎正在做的是追加Team HTML
然后追加Players HTML
,然后追加Team HTML
和Players HTML
等等。您应该将Players HTML
添加到Team HTML
,然后将Team HTML
添加到el
。试试这是否有效:
this.teams.each(function(team) {
var teamView = new TeamView({ model: team });
var teamHtml = teamView.render().el;
var teamPlayers = this.players.where({team_id: team.get('id')})
console.log(teamPlayers)
_.each(teamPlayers, function(player) {
var playerView = new PlayerView({ model: player });
var playerHtml = playerView.render().el;
// Add player HTML to Team HTML
$(teamHtml).find('div').append(playerHtml);
console.log(player.toJSON());
}, this);
// Add Team HTML to el
this.$el.append(teamHtml);
}, this);
这只是你正在做的事情,但你应该考虑以更好的方式构建你的观点。