【发布时间】:2012-02-27 14:30:11
【问题描述】:
我正在尝试使用 Underscore.js 模板将 Backbone.js 集合呈现为 select 列表,但该列表没有被填充。 select 元素正在显示,但没有 options。
我已经确认我能够将单个属性传递到我的模板中并将它们呈现为label 元素,所以问题一定是我尝试如何处理集合。
这是我的主干代码:
Rate = Backbone.Model.extend({
duration : null
});
Rates = Backbone.Collection.extend({
initialize: function (model, options) {
}
});
AppView = Backbone.View.extend({
el: $('#rate-editor-container'),
initialize: function () {
this.rates = new Rates(null, { view: this } );
this.rates.add(new Rate ({ duration: "Not Set" }));
this.rates.add(new Rate ({ duration: "Weekly" }));
this.rates.add(new Rate ({ duration: "Monthly" }));
this.render();
},
render: function() {
var rate_select_template = _.template($("#rate_select_template").html(), {rates: this.rates, labelValue: 'Something' });
$('#rate-editor-container').html(rate_select_template);
},
});
var appview = new AppView();
还有我的模板:
<script type="text/template" id="rate_select_template">
<select id="rate-selector"></select>
<% _(rates).each(function(rate) { %>
<option value="<%= rate.duration %>"><%= rate.duration %></option>
<% }); %>
</script>
<div id="rate-editor-container"></div>
有什么建议吗?
【问题讨论】:
-
再次检查渲染函数中“this”的值 - 我没有看到您将它绑定到 Backbone 对象。您可以在初始化函数中使用 _.bindAll(this, 'render') 来完成。
-
嗯。我在我的
Backbone.View扩展中将它添加到this.render()的正上方,但它似乎没有做任何事情。在我发布我的问题之前,我做了console.log(this.rates),它输出为child,带有三个子对象。所以我想我正在传递某种对象,其中嵌套了三个对象,这似乎是正确的。 -
@Factor:
delegateEvents在 Backbone 的最新版本中自己进行绑定(在delegateEvents中查找method = _.bind(method, this);在 latest source 中),因此您不再需要通常的_.bindAll跳舞开始你的initialize方法。
标签: javascript backbone.js underscore.js