【发布时间】:2014-04-26 04:39:46
【问题描述】:
我遇到了这个我无法理解的主干/下划线模板绑定问题。
下划线模板提供了一个对象集合,但是在遍历集合并构建生成的 HTML 时,并非所有单个对象的属性都被解析。
- 我相信模板正确接收集合(异步调用服务器)。我已经调试了收到的集合并正确填充了它。
- 我已经“渲染”了 HTML 中的原始集合项,以验证我正在处理正确的对象...所有显示都正确。
我在这里简化了代码,希望不会混淆问题。点击事件负责选择一个部分(代码中不包含)
代码如下:
//Underscore Template
<script id="articles-template2" type="text/html">
<table>
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Date</th>
<th>Data</th>
</tr>
</thead>
<tbody>
<% _.each(articles, function(a){ %>
<tr>
<td><%= JSON.stringify(a)%></td>
<td><a href="#" data-id="<%= a.id%>"><%= a.title %></a></td>
<td><%= a.description%></td>
<td><%= new Date(a.date)%></td>
</tr>
<%});%>
</tbody>
</table>
</script>
// Backbone View ----------------
window.ArticlesView2 = Backbone.View.extend({
initialize: function () {
var self = this;
self.collection.on("reset", this.render, this);
},
template: _.template($('#articles-template2').html()),
render: function () {
var self = this;
$(self.el).html(self.template({ articles: self.collection.models }));
$('#section-list').append(self.el);
return self;
},
events: {
"click a": "clicked"
},
clicked: function (e) {
var self = this;
e.preventDefault();
var id = $(e.currentTarget).data("id");
var item = self.collection.get(id);
var name = item.get("title");
alert(name);
}
});
// Router ----------------
var AppRouter = Backbone.Router.extend(
{
routes: {
'section/:title': 'viewSection'
},
viewSection:function(section)
{
var self = this;
self.articles = new ArticleList({ selectedSection: section });
self.view = new ArticlesView2({ collection: self.articles });
self.articles.fetch({ reset: true });
}
}
);
// Initialize ----------------
var app = new AppRouter();
Backbone.history.start();
app.navigate('section/Home', { trigger: true });
渲染出来的 HTML 如下:
<table>
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Date</th>
<th>Data</th>
</tr>
</thead>
<tbody>
<tr>
<td>{"id":"527c61082241f813c09c7041","title":"title here","description":" test descript here","date":"2005-02-08T05:00:00.0000000Z"}</td>
<td><a href="#" data-id="527c61082241f813c09c7041"></a></td>
<td></td>
<td>Invalid Date</td>
</tr>
</tbody>
</table>
我不确定为什么可以 Stringfy() 对象并获取数据但无法成功查询其属性?????? 这是一个事件问题,伙计,我错过了什么? 谢谢
【问题讨论】: