如何使用Backbone + Underscore模板对选择元素进行数据绑定?

时间:2016-01-14 21:49:22

标签: backbone.js underscore.js-templating

假设我想使用Underscore模板渲染表单。在教程之后,我在Backbone视图中输入了类似的内容:

<table>
    <tr>
        <td rowspan="2"><h1>Some big text</h1></td>
        <td><p><strong>Some</strong></p>
        <td><p><strong>smaller text</strong></p></td>
    </tr>
    <tr>
        <td><p><strong>Here come</strong></p></td>
        <td><p><strong>Second row</strong></p></td>
</table>

在我的模板中,例如

table {
    width: 80%; 
    margin-left: 2%; 
    border-collapse: separate; 
    border-spacing: 0 1px;
}

table tr td {
    padding: 0;
}

table tr td h1 {
    margin: 0;
}

table tr td p {
    margin: 0;
}

这一切都很好,但如果我的表单包含var CatFormView = Backbone.View.extend({ render: function () { this.$el.html(this.template(this.model.toJSON())); } )}; 元素怎么办?我可以这样做:

<label for="cat-name">Cat name:</label>
<input id="cat-name" value="<%- catName %>" />

或者我是否直接在模板中绑定select元素,然后在视图中设置<select id="cat-breed"> <option value="siamese" <% if (catBreed === "siamese") { %> selected <% } %>>Siamese</option> <option value="persian" <% if (catBreed === "persian") { %> selected <% } %>>Persian</option> <option value="scottish-fold" <% if (catBreed === "scottish-fold") { %> selected <% } %>>Scottish Fold</option> ... </select> 的值?

第一种方法看起来非常麻烦,第二种方法将数据绑定逻辑分散在几个文件上,使得Web应用程序的可维护性降低。

这里有什么更好的解决方案?

编辑:循环!现在它看起来很明显,但我仍然坚持认为Underscore模板是标记。非常感谢Clémentine。

input

编辑2 :或者,甚至更好(并且可重复使用):

select

1 个答案:

答案 0 :(得分:1)

另一种选择是为您的表单使用其他模型,例如

[
{
'id': 'cat-breed',
'type': 'select',
'values': ["siamese", "scottish-fold", "persian"]
}
]

然后致电

this.template(data_model: this.model.toJSON(), form_model:this.form_model.toJSON())

然后使用循环构建表单和表单答案。

这将允许您拥有更通用的模板系统,减少繁琐,但更难编码。