Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Knockout to group foreach

Tags:

knockout.js

I can get my records to repeat using foreach, but because I'm using a grid system for CSS, I want to group these records four at a time (div class="column") for each (div class="row").

I'm not seeing a good example how to wrap each each record this way.

Any help?

like image 424
Chris Avatar asked May 13 '12 22:05

Chris


1 Answers

So I'm not entirely sure what you are after but you could you group manually like this.

http://jsfiddle.net/madcapnmckay/hFPgT/1/

<div data-bind="foreach: grouped" >
    <div data-bind="foreach: $data" class="row">
        <div class="column" data-bind="text: text"></div>
    </div>
</div>    

this.grouped = ko.computed(function () {
        var rows = [], current = [];
        rows.push(current);
        for (var i = 0; i < this.items.length; i += 1) {
            current.push(this.items[i]);
            if (((i + 1) % 4) === 0) {
                current = [];
                rows.push(current);
            }
        }
        return rows;
}, this);

Hope this helps.

like image 101
madcapnmckay Avatar answered Nov 11 '22 16:11

madcapnmckay