Create columns with the foreach of knockoutJS

1

Good afternoon, I wanted to 'break' a list of items in 3 columns of 4 items in a foreach of knockoutJS.

That is, at this point the list is populated down and I would like it to be broken via jQuery or javascript because CSS is not supported in IE9

Thanks for the help!

var lbx = {};
var json = {
  "items": [{
    "key": 13,
    "value": "A. E. Brehm"
  }, {
    "key": 14,
    "value": "Achille Murat"
  }, {
    "key": 15,
    "value": "Adolphe Siret"
  }, {
    "key": 16,
    "value": "Adrien Balbi"
  }, {
    "key": 18,
    "value": "Albereto de Oliveira"
  }, {
    "key": 19,
    "value": "Alberto dos Reis"
  }, {
    "key": 20,
    "value": "Albino Forjaz de Sampaio"
  }, {
    "key": 21,
    "value": "Alexandre Dumas"
  }, {
    "key": 22,
    "value": "Alexandre Herculano"
  }, {
    "key": 23,
    "value": "Alfredo França"
  }, {
    "key": 24,
    "value": "Allen Ginsberg"
  }, {
    "key": 25,
    "value": "Alphonse Allais"
  }],
  "totalItems": 261
};

lbx.vm = {
  term: ko.observableArray(),
};


lbx.vm.term.push(json);

console.log(lbx.vm.term());

$(function() {

  ko.applyBindings(lbx.vm);

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="list-unstyled" data-bind="foreach: term">
  <ul data-bind="foreach: items">
    <li data-bind="text: value">
    </li>

  </ul>
</div>
    
asked by anonymous 22.03.2016 / 18:42

1 answer

1

Well, I found this example from someone else in another American forum. Maybe it will help.

As I understand it, it uses a ko.computed to work with the columns, not forgetting to determine the number of columns.

I think this might help you.

var viewModel = {
  items: ko.observableArray(),
  columnLength: ko.observable(5)
};

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.computed(function() {
  var result = [],
    row,
    colLength = parseInt(this.columnLength(), 10);

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

ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input data-bind="value: columnLength" />
<hr/>

<table data-bind="foreach: rows">
  <tr data-bind="foreach: $data">
    <td data-bind="text: name"></td>
  </tr>
</table>

Credits to: rniemeyer JSFiddle     

22.03.2016 / 20:13