Introduction
$index
is the feature of the knockout.js to point current items index in array. But there are some differences in its uses. Here, let’s see how we can use it in both HTML DOM and inside view model itself.
Why Do We Need This $index
- To use items real index in HTML DOM.
- To show serial numbers of the item in HTML DOM, especially in data tables.
- Sometimes, we may have to get the index of the current item in view model itself too.
Using the Code
Here is the overall HTML DOM and view model code for the solution, JsFiddle.
HTML DOM:
<table>
<thead>
<tr>
<td>Index</td>
<td>Serail</td>
<td>Item</td>
<td>Show Index from inside Vm</td>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<!--
<td data-bind="text: $index"></td>
<!--
<td data-bind="text: $index() + 1"></td>
<td data-bind="text: $data"></td>
<td><a href="#" data-bind="click:
$root.showItemIndex">Show</a></td>
</tr>
</tbody>
</table>
View Model:
function ViewModel() {
var self = this;
self.items = ko.observableArray([]);
self.showItemIndex = function (item, event) {
var context = ko.contextFor(event.target);
var index = context.$index();
alert('The item index: ' + index);
};
self.init = function() {
var arr = ['CSE', 'EEE', 'IPE', 'BBA'];
self.items([]);
self.items(arr);
};
}
$(document).ready(function () {
var vm = new ViewModel();
ko.applyBindings(vm);
vm.init();
});
$index in DOM
<!--
<td data-bind="text: $index"></td>
Serial Number using $index in DOM
<!--
<td data-bind="text: $index() + 1"></td>
Item Index Inside the View Model
self.showItemIndex = function (item, event) {
var context = ko.contextFor(event.target);
var index = context.$index();
alert('The item index: ' + index);
};