Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index value while using ko.utils.arrayForEach

I am using ko.utils.arrayForEach as mentioned below.

ko.utils.arrayForEach(comments , function(comment) {
    tmp.push(comment);
});

Here I am getting all the results and they are pushed to tmp. If I want to access the first record alone, how can I modify the above code for retrieving the index.

like image 760
Mahahari Avatar asked Feb 20 '14 06:02

Mahahari


2 Answers

Since version 3.1.0 released on 14 May 2014, index is passed to all the array functions as the second argument:

ko.utils.arrayForEach(items, function(item, index) {
    /* ... */
});
like image 109
Andrea Casaccia Avatar answered Oct 28 '22 18:10

Andrea Casaccia


Unfortunately, it's not possible yet. PimTerry added this functionnality on December (see this commit), but it has not be release yet.

Until now; you can do it manually:

for (var i = 0, j = comments.length; i < j; i++) {
  // use an anonymous function to keep the same code structure
  (function(comment, i) {
    tmp.push(comment);
    // do what you need with i here
  })(comments[i], i);
}

It's exaclty the code used inside ko.utils.arrayForEach. The migration will be very easy once Knockout will be released

like image 31
Feugy Avatar answered Oct 28 '22 19:10

Feugy