我想使用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