Luke Puplett
Luke Puplett

Reputation: 45135

How do I for-each over a Knockout.JS observableArray?

All attempts to iterate over a KO observableArray have failed. The flow just jumps over the block like the array is empty.

It's not, because its bound to some HTML and the debugger shows 7 items.

I've tried a normal for with an indexer, an ECMA-5+ forEach and now KO's own arrayForEach utility.

var EditorViewModel = function (firstDayOfWeek) {

    this.firstDayOfWeek = firstDayOfWeek;
    this.days = ko.observableArray([]); // Added in server-side generated view below.

    // Reads the activity data from each day and constructs and uploads models.
    this.save = function () {

        var basket = [];

        // Construct the upload activity models.

        ko.utils.arrayForEach(this.days(), function(d) {

            ... // never falls into this block.

There's nothing much out on the web about this, so I guess its a no-brainer. I'm obviously messing it up somehow, but its eluding me this afternoon.

this.days array looks good to me.

Dump of debugger showing 7 items in array

Thanks, Luke

Upvotes: 3

Views: 11498

Answers (2)

Luke Puplett
Luke Puplett

Reputation: 45135

I don't know why its not working with the forEach methods, but I did get it going with a properly written traditional for index iterator.

for (dayIndex = 0; dayIndex < this.days().length; dayIndex++) { ... }

Upvotes: 0

Pushker Yadav
Pushker Yadav

Reputation: 856

here days is a observableArray which is nothing but a function , to iterate you need to read the value like days() , this is will give you a javascript array.

var days = ko.observableArray([1,3,4,5,6]);

days().forEach(function(v,i){
  alert(v);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

Upvotes: 6

Related Questions