有没有人使用 Backbone.js 将垂直表格列用作 View “el”取得了成功?由于表格是基于行的,因此使用表格行作为与 View 关联的 DOM 容器是微不足道的。但是,我需要实现的布局是垂直的,因此表格列将是我设计的“el”,但表格列没有类似的容器元素,因为表格布局是水平的。
到目前为止,我还没有能够成功地为表列创建 subview ,这意味着我将数据绑定(bind)到我的 DOM 以便检索和操作表列。我的设计变得更加复杂,这促使我重新评估最初的方法,希望有更好的方法通过 subview 来管理这种情况。有什么想法吗?
最佳答案
你可以利用这个事实
- jQuery 对象是 DOM 元素的列表
- Backbone 不需要唯一的 DOM 节点(至少据我所知) View 中的
this.$el
可以是您想要的任何节点
考虑到这一点,您可以一次性渲染您的表格(请参阅 BackboneJS Rendering Problems ,它更快,并且在您的情况下可能更容易),然后将您的 subview 应用于与模型关联的表格单元格。我使用类名进行选择,但每行第 n 个元素上的选择器应该可以工作。
模板
<table>
<thead>
<tr>
<th></th>
<% _(children).each(function(model) { %>
<th><%= model.id %></th>
<% }); %>
</tr>
</thead>
<tbody>
<% _(properties).each(function(prop) { %>
<tr>
<td><%= prop %></td>
<% _(children).each(function(model) { %>
<td class="<%= model.cid %>"><% print(model[prop]); %></td>
<% }); %>
</tr>
<% }); %>
</tbody>
</table>
查看
ListView = Backbone.View.extend({
initialize: function(opts) {
this.options = opts;
},
render: function () {
var data, html, $table, template = this.options.template;
data = this.collection.map(function (model) {
return _.extend(model.toJSON(), {
cid: model.cid
});
});
html = this.options.template({
children: data,
properties: ['id', 'name']
});
$table = $(html);
this.collection.each(function (model, ix) {
var $el = $table.find("." + model.cid),
subview = new ItemView({
el: $el,
model: model
});
});
this.$el.empty();
this.$el.append($table);
return this;
}
});
您可以查看此演示 http://jsfiddle.net/nikoshr/psasT/12/ ,每一列都由一个专用 View 处理。
关于javascript - Backbone View el 作为表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14447283/