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?
$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.
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.
var viewModel = ko.mapping.fromJS(data); This automatically creates observable properties for each of the properties on data .
knockout 2.1 has added good new option $index. Here is example http://knockoutjs.com/documentation/foreach-binding.html
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With