Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js print index of object in foreach

Tags:

knockout.js

This is probably quite simple but I can't seem to find it readily. In knockout.js, How would you print the index of an item in an observable array that you are iterating over using the foreach binding?

like image 917
Graham Conzett Avatar asked Mar 28 '12 18:03

Graham Conzett


People also ask

What is $root in knockout?

$root. This is the main view model object in the root context, i.e., the topmost parent context. It's usually the object that was passed to ko. applyBindings . It is equivalent to $parents[$parents.

For what purpose do we use forEach binding in Ko?

Purpose. The foreach binding duplicates a section of markup for each entry in an array, and binds each copy of that markup to the corresponding array item. This is especially useful for rendering lists or tables.

What is Ko mapping fromJS?

var viewModel = ko.mapping.fromJS(data); This automatically creates observable properties for each of the properties on data .


2 Answers

knockout 2.1 has added good new option $index. Here is example http://knockoutjs.com/documentation/foreach-binding.html

like image 166
Ashish Avatar answered Oct 19 '22 08:10

Ashish


You can't. Not directly anyway. I use this function myself to add an index property to objects in my ObservableArrays:

    function indexSubscribe(array) {
        array.subscribe(function() {
            for (var i = 0, j = array().length; i < j; i++) {
                var item = array()[i];
                if (!item.index) {
                    item.index = ko.observable(i);  
                } else {
                    item.index(i);  
                }
            }
        }); 
   };

Then in my ViewModel, I can do something like this:

this.whatevers = ko.observableArray();
indexSubscribe(this.whatevers);
like image 24
Matt Burland Avatar answered Oct 19 '22 08:10

Matt Burland