Knockout.js - 动态列,但每行最多 5 个 [英] Knockout.js - Dynamic columns but limit to a maximum of 5 for each row
问题描述
我在这里找到了一个类似的问题/答案:如何呈现包含一些固定列和一些动态列的表格
I found a similar question/answer here: How to render a table with some fixed and some dynamic columns
但它并没有完全解决我的问题.我想弄清楚如何将动态列的数量限制为每行 5 个,如果视图模型中有 5 个以上的项目,则创建一个新行并为数组中的所有 5 组重复此操作.
But it does not completely solve my problem. I am trying to figure out how I can limit the number of dynamic columns to 5 per row and if there are more than 5 items in the view model, make a new row and repeat for all groups of 5 in the array.
例如:
var vm = {
item: { name: 'test1' },
item: { name: 'test2' },
item: { name: 'test3' },
item: { name: 'test4' },
item: { name: 'test5' },
item: { name: 'test6' }
};
给那个模型,我怎样才能得到这个表?
Give that model, how can I get this table?
<table>
<tr>
<td>test1</td>
<td>test2</td>
<td>test3</td>
<td>test4</td>
<td>test5</td>
</tr>
<tr>
<td>test6</td>
<tr>
</table>
推荐答案
为了处理这样的情况,我可能会将逻辑推送到您的视图模型中,以便您的视图保持简单.所以这个想法是使用一个dependentObservable 来表示你的行".然后,您的视图可以只对行进行 foreach,然后对行中的单元格进行 foreach.
To handle a situation like this, I would probably push the logic into your view model, so that your view can remain simple. So the idea would be to use a dependentObservable to represent your "rows". Then, your view can just foreach through the rows and then foreach through the cells in your row.
这是一个示例,该示例使该列数成为可观察的,以便可以动态更新.http://jsfiddle.net/rniemeyer/9TN9W/
Here is a sample that makes that number of columns an observable, so that it can be dynamically updated. http://jsfiddle.net/rniemeyer/9TN9W/
var viewModel = {
items: ko.observableArray(),
columnLength: ko.observable(5)
};
//sample data
for (var i = 0; i < 100; i++) {
viewModel.items.push({ name: 'test' + i });
}
//return an array of rows. Each row is an array of items
viewModel.rows = ko.dependentObservable(function() {
var result = [],
colLength = parseInt(this.columnLength(), 10),
row;
//loop through items and push each item to a row array that gets pushed to the final result
for (var i = 0, j = this.items().length; i < j; i++) {
if (i % colLength === 0) {
if (row) {
result.push(row);
}
row = [];
}
row.push(this.items()[i]);
}
//push the final row
if (row) {
result.push(row);
}
return result;
}, viewModel);
这篇关于Knockout.js - 动态列,但每行最多 5 个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!