Knockout js foreach binding large data into row by

2019-09-20 06:34发布

问题:

I have a Data binding like below using knockout and bootstrap css. i have this degreeCodes jSON that has let's say 40 items. but on UI side i only want 4 on each <div class="row" >

the 5th one should create a new <div class="row" > and add the content there. so if it worked correctly it would have 10 <div class="row" > and each with 4 items of

<label class="text-muted" data-bind="text: DegreeName"></label>

how can i do a template like that? Where it adds a new div class row when it reaches n mod 4 =0 where n is the current item from jsonview being binded? i am ok with adding a parent div if that helps

<div class="row" data-bind="foreach: degreeCodes">
                <label class="text-muted" data-bind="text: DegreeName">></label>
<div>

if it worked correctly it would be rendering something like...

   <div class="row" data-bind="foreach: degreeCodes">
                    <label class="text-muted" data-bind="text: DegreeName"> Degree1</label>
                    <label class="text-muted" data-bind="text: DegreeName"> Degree2</label>
                    <label class="text-muted" data-bind="text: DegreeName"> Degree3</label>
                    <label class="text-muted" data-bind="text: DegreeName"> Degree4</label>
    <div>

        <div class="row" data-bind="foreach: degreeCodes">
                    <label class="text-muted" data-bind="text: DegreeName"> Degree5</label>
                    <label class="text-muted" data-bind="text: DegreeName"> Degree6</label>
                    <label class="text-muted" data-bind="text: DegreeName"> Degree7</label>
                    <label class="text-muted" data-bind="text: DegreeName"> Degree8</label>
    <div>

回答1:

I'd create a computed that simply returns an array of 4-element subarrays from the original array, and then use two nested foreach loops; the outer one would probably be a containerless binding looping over the computed array, with the inner one being similar to what you're doing now, looping over each 4-array.

Something like:

vm.byFour=ko.computed(function() {
  var source=ko.unwrap(vm.degreeCodes);
  var result=[];
  for (var i=0; i<source.length; i+=4) {
    result.push(source.slice(i, i+4);
  }
  return result;
});

...

<!-- ko: foreach: {data: byFour, as: degreeCodes} -->
<div class="row" data-bind="foreach: degreeCodes">
   <label class="text-muted" data-bind="text: DegreeName">></label>
<div>
<!-- /ko -->


回答2:

Knockout's foreach binding is not sophisticated enough to handle this. You'll need to subdivide your data, so that you essentially have an array of arrays with just four items. Then you can do a nested foreach to loop through them all.