我对 Backbone 和下划线中的第一个模板化视图不太满意。
我从 Underscore 库中收到“未定义玩家错误”。
这是我的模型:
define([
'domLib',
'underscore',
'backbone',
'router'
],
function($, _, Backbone, Router) {
var PlayerModel = Backbone.Model.extend({
defaults: {
username: '',
rank: 0,
score: 0
}
});
return PlayerModel;
});
这是我的收藏:
define([
'domLib',
'underscore',
'backbone',
'router',
'model/player'
],
function($, _, Backbone, Router, PlayerModel) {
var LeaderboardCollection = Backbone.Collection.extend({
model: PlayerModel,
url: '/hyc-web/leaderBoard/topOverall?count=5'
});
return LeaderboardCollection;
});
相关视图:
define([
'domLib',
'underscore',
'backbone',
'router',
'collection/leaderboard',
'text!template/leaderboard.html'
],
function($, _, Backbone, Router, LeaderboardCollection, LeaderboardTemplate) {
var LeaderboardView = Backbone.View.extend({
el: '#leaderboard',
template: _.template(LeaderboardTemplate),
initialize: function(){
this.collection = new LeaderboardCollection();
this.collection.on('reset', this.render, this);
this.collection.fetch();
},
render: function(){
console.log(this.collection.models);
this.$el.html(this.template, {players: this.collection.models});
}
});
return LeaderboardView;
});
和模板本身:
<table class="table table-bordered">
<thead>
<tr>
<td>Rank</td>
<td>Player</td>
<td>Score</td>
</tr>
</thead>
<tfoot>
<!-- Logged in user details here -->
</tfoot>
<tbody>
<% _.each(players, function(player){ %>
<tr>
<td><%= player.rank %></td>
<td><%= player.username %></td>
<td><%= player.highScore %></td>
</tr>
<% }); %>
</tbody>
</table>
一切都很顺利,直到我尝试连接到实际的数据服务层。我不明白为什么这不是模板化 JSON 数组?