Knockout JS: foreach, which is increasing by 2

In Knockout JS, can I make a foreach that increases by 2? Something like:

 for (var i = 0; i < array.length; i += 2) { // Do stuff } 

The reason I would like to do this is because the data I need to scroll is an array, not an object. Example:

 viewModel = function () { this.facets = ["Sample", 100, "Sample 2", 200]; } 

But the data should be displayed as follows:

 <ul data-bind="foreach: facets"> <!-- Can this foreach be incremented by 2? --> <li>$data[$index]: $data[$index + 1]</li> </ul> 

Any help would be greatly appreciated.

+4
source share
4 answers

You can write a special binding handler for this, but I would prefer to leave the templates free from such ugly details.

I would recommend writing ko.computed :

 function Model() { this.data = ko.observableArray(["Sample", 100, "Sample 2", 200]) this.items = ko.computed(function() { var value = []; var data = this.data(); for (var i=0; i<data.length; i+=2) { value.push({ key: data[i], value: data[i+1]); } return value; }, this); } var model = new Model(); 

Now you can iterate over items in your template and access key and value . Updating the original data array will automatically restore the calculated items value.

The template code will look like this:

 <ul data-bind="foreach: items"> <li><span data-bind="text: key"></span>: <span data-bind="text: value"></span></li> </ul> 
+5
source

Repeat binding ( https://github.com/mbest/knockout-repeat ) allows you to specify the step option.

 <ul> <li data-bind="repeat: {foreach: facets, step: 2}" data-repeat-bind="text: facets[$index] + ': ' + facets[$index+1]"> </li> </ul> 
+2
source

This is probably what you are looking for:

 for (var i = 0; i < array.length; i += 2) { var sample = array[i]; var number = array[i+1]; var display = "<li>" + sample + ": " + number + "</li>" // display this } 

It looks like you already have this, so I'm not sure what the problem is ...

+1
source

You can use the function to create a structure for which you need to bind:

  self.arrayFunc = function() { var result = []; for (var i = 0, length = array.length; i += 2) { result.push({first: array[i], second: [i + 1]}; } }; 
0
source