Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

javascript - 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

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.

For example:

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...