0

How would I accomplish something like this in Knockout? Given the source is something like this ["One", "Two", "Three"]

<div>
    <p>
        <div>
            <div>One</div>
            <div>Two</div>
            <div>Three</div>
        </div>
        <div>
            <div>Four</div>
            <div>Five</div>
            <div>Six</div>
        </div>
    </p>
</div>
user3072624
  • 57
  • 1
  • 4
  • What you have done here is to recreate a table in the form of div's. In the dark days of table design we needed to do it like this. You should instead just create one div per row in array and use CSS to fix the layout. Also divs in p's are not valid – Anders Feb 20 '14 at 07:18

2 Answers2

0
<div data-bind="foreach:someArrayContainingTheValues">
    <div data-bind="text:$data"></div>
</div>

Try the above

TGH
  • 38,769
  • 12
  • 102
  • 135
0

I've created a JSFiddle to show a sample of how this can be achieved: http://jsfiddle.net/bxfXd/3509/

Markup:

<div class="outer" data-bind="foreach:itemsGrouped">
    <div class="inner">
        <!-- ko foreach: $data -->
            <div class="main" data-bind="text:$data"></div>
        <!-- /ko -->
    <div>
</div>

JS:

Array.prototype.chunk = function (chunkSize) {
    var array = this;
    return [].concat.apply([],
    array.map(function (elem, i) {
        return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
    }));
}

var SimpleListModel = function(items) {
    var self = this;

    self.items = ko.observableArray(items); 

    self.itemsGrouped = ko.computed(function () {
        return self.items().chunk(3);
    });
};

ko.applyBindings(new SimpleListModel(
                            ["One", "Two", "Three", "Four", "Five", "Six"]));

For reference, the chunk method was taken from here, posted by @ninjagecko

Community
  • 1
  • 1
Tanner
  • 22,205
  • 9
  • 65
  • 83