Knockout.js - 动态列,但每行最多限制为5 [英] Knockout.js - Dynamic columns but limit to a maximum of 5 for each row

查看:108
本文介绍了Knockout.js - 动态列,但每行最多限制为5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里找到了类似的问题/答案:如何使用一些固定列和一些动态列呈现表格

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来表示您的行。然后,您的视图可以遍历行,然后遍历行中的单元格。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆