Question

I'd like to take an array like this:

var items = [1,2,3,4,5,6]

and bind it in KnockoutJS so that the output rendered is:

<div class="row">
 <div class="col-md-4">1</div>
 <div class="col-md-4">2</div>
 <div class="col-md-4">3</div>
</div>
<div class="row">
 <div class="col-md-4">4</div>
 <div class="col-md-4">5</div>
 <div class="col-md-4">6</div>
</div>

This would be straightforward if it were not for the need to close and open a new row every three items. Any suggestions would be appreciated!

Thanks...

-Ben

Was it helpful?

Solution

Assuming that items will be updated while the application is running:

var model = {};

model.items = ko.observable([1,2,3,4,5,6]);

model.renderedItems = ko.computed(function() {
  var data = model.items();
  var times = Math.ceil(items.length / 3);
  var result = [];
  for (var i = 0; i < times; i ++) {
    result.push(data.slice(i * 3, i * 3 + 3));
  }
  return result;
});

Now bind renderedItems to a template that will have two nested foreach bindings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top