【发布时间】:2015-02-21 23:27:20
【问题描述】:
我正在尝试使用木偶制作一个具有动态行数和列数的表格网格,并带有标题。
我想要一个看起来像这样的网格:http://jsfiddle.net/zaphod013/c3w61gf6/
所以有
columns = ['早餐', '午餐', '晚餐']
rows = ['carbs', 'proteins', 'fats']
网格的其余部分是复选框。
我已经为列和行创建了视图,但是我对如何将它们放入表中以及如何添加复选框视图感到很困惑。
我的代码是http://jsfiddle.net/zaphod013/qkctrLxn/
html:
<div id="main-region"></div>
<script id="food-table" type="text/template">
<thead id="column-id">
</thead>
<tbody id="row-id">
</tbody>
</script>
<script id="food-col-item" type="text/template">
<th><%= col %></th>
</script>
<script id="food-row-item" type="text/template">
<td><%= row %></td>
</script>
script:
FoodManager = new Backbone.Marionette.Application();
FoodManager.addRegions({
mainRegion: "#main-region",
});
FoodManager.FoodLayout = Backbone.Marionette.Layout.extend({
template: "#food-table",
regions: {
colRegion:"#column-id",
rowRegion:"#row-id"
}
});
FoodManager.Col = Backbone.Model.extend({});
FoodManager.ColCollection = Backbone.Collection.extend({
model: FoodManager.Col
});
FoodManager.Row = Backbone.Model.extend({});
FoodManager.RowCollection = Backbone.Collection.extend({
model: FoodManager.Row
});
FoodManager.ColItemView = Marionette.ItemView.extend({
template: "#food-col-item",
tagName: "th",
});
FoodManager.ColView = Marionette.CompositeView.extend({
template: "#food-table",
tagName: "thead",
itemView: FoodManager.ColItemView
});
FoodManager.RowItemView = Marionette.ItemView.extend({
template: "#food-row-item",
tagName: "th",
});
FoodManager.RowView = Marionette.CompositeView.extend({
template: "#food-table",
tagName: "table",
itemView: FoodManager.RowItemView
});
FoodManager.on("initialize:after", function(){
var columns = new FoodManager.ColCollection([
{col: 'Breakfast'},
{col: 'Lunch'},
{col: 'Dinner'}
]);
var rows = new FoodManager.RowCollection([
{row: 'Carbs'},
{row: 'Protein'},
{row: 'Fats'}
]);
var colListView = new FoodManager.ColView({
collection: columns
});
var rowListView = new FoodManager.RowView({
collection: rows
});
var foodLayout = new FoodManager.FoodLayout();
foodLayout.render();
FoodManager.colRegion.show(colListView);
FoodManager.rowRegion.show(rowListView);
FoodManager.mainRegion.show(foodLayout);
});
FoodManager.start();
我将非常感谢一些关于如何解决此问题的建议。
感谢您的通读。
【问题讨论】:
-
“动态的行数和列数”是什么意思?你所描述的对我来说似乎不是动态的。动态意味着每次呈现表格时可能会有不同的数字,具体取决于您加载的数据。据我了解,您想要的表格总是三列三行。
-
html 示例显示 3 行 3 列作为渲染示例。但是如果你看 js 代码,行和列是集合,因此是动态的。
-
作为建议,构建在另一个已经有坚实基础的框架之上。我在使用 BackgridJS 做类似事情时有很好的经验:backgridjs.com。列被描述为模型属性;行只是模型。单元格的渲染非常灵活。 Backgrid 的核心组件是可扩展的,甚至是可替换的。
-
听起来您正在寻找的是一个需要多个集合的 CompositeView。不幸的是,目前 Marionette 库中不提供该功能。您的 HTML 不会验证,但您可以使用 LayoutView 执行您建议的操作。如果您需要帮助,请告诉我。
-
@Seebiscuit,我确实需要一些有关布局的帮助。我无法超越这个阶段。我想我在这里遗漏了一些关键概念。
标签: javascript backbone.js marionette