【发布时间】:2013-04-14 13:48:07
【问题描述】:
我在 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 数组的模板?
【问题讨论】:
-
this.$el.html(this.template, {players: this.collection.models});是错字吗?因为在我看来你没有在这里评估模板。 -
好吧,所以我改变了我的看法: var compiledTemplate = _.template(LeaderboardTemplate, {players: this.collection.models}); this.$el.html(compiledTemplate);
-
但它似乎没有遍历数组?
-
你试过 吗?如果这不起作用,我使用this 简单的技巧来调试下划线模板。 (它适用于任何具有脚本调试器的浏览器)
标签: javascript templates dom backbone.js underscore.js