我想使用Underscore.js模板呈现Backbone.js集合作为select
列表,并且列表未被填充。 select
元素正在显示,但没有options
。渲染Backbone.js集合作为选择列表
我已确认我可以将单个属性传递到我的模板并将它们呈现为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')来完成它。 – 2012-02-06 01:15:15
嗯。我在我的'Backbone.View'扩展中添加了'this.render()',但它似乎没有做任何事情。在我发布我的问题之前,我做了'console.log(this.rates)',并将它输出为具有三个子对象的'child'。所以我认为我传递了一个嵌套在它下面的三个对象的某种对象,这看起来是正确的。 – 2012-02-06 01:19:43
@Factor:在最近版本的Backbone中的'delegateEvents'自己完成绑定(查找'method = _。在[latest source](http://documentcloud.github.com/backbone/backbone.js)中绑定(method,this);''delegateEvents''内部,所以你不再需要通常的'_.bindAll'跳舞开始你的'initialize'方法。 – 2012-02-06 01:46:53