Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout - foreach databind in 2 column table layout

I have the following table where I'm attempting to loop through coverage lines. I would like 2 columns with a different line in each, however my code duplicates the same coverage in each column. Any suggesions on how to get a 2 column layout without the repetition? Which element should my foreach binding go on? Thanks.

        <table class="coverage-table" data-bind="foreach: $root.clientVM.CustomCoverageLines">
            <tr>
                <td>
                    <input type="checkbox" data-bind="checked: Checked" />
                    <label>
                        <span data-bind="text: $data.Description"></span>
                    </label>
                </td>
                <td>
                    <input type="checkbox" data-bind="checked: Checked" />
                    <label>
                        <span data-bind="text: $data.Description"></span>
                    </label>
                </td>
            </tr>
        </table>
like image 547
noclist Avatar asked Apr 28 '26 21:04

noclist


1 Answers

You could add a computed property to your model that structures the data in the way that you want. See this JSFiddle for an example: http://jsfiddle.net/6gvtz51g/. An advantage to this approach is that you can specify a different row size if you would like.

HTML

<table data-bind="foreach: coverageLineRows">
    <tr data-bind="foreach: $data">
        <td>
            <span data-bind="text: $data"></span>
        </td>
    </tr>
</table>

JavaScript

function ViewModel () {
    var self = this;

    self.coverageLines = ko.observableArray([
        'Medical',
        'Dental',
        'Vision',
        'Life'
    ]);
    self.coverageLineRowSize = ko.observable(2);
    self.coverageLineRows = ko.computed(function () {
        var rows = [];
        var i = 0;
        var lines = self.coverageLines();
        var size = self.coverageLineRowSize();

        while (i < lines.length) {
            rows.push(lines.slice(i, i += size));
        }

        return rows;
    });
}

ko.applyBindings(new ViewModel());
like image 135
Drew Gaynor Avatar answered Apr 30 '26 12:04

Drew Gaynor