65.9K
CodeProject is changing. Read more.
Home

Using $index in Knockout.js

Jul 16, 2014

CPOL
viewsIcon

29366

downloadIcon

34

Using $index in Knockout.js

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

  1. To use items real index in HTML DOM.
  2. To show serial numbers of the item in HTML DOM, especially in data tables.
  3. 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>
            <!--item index in array-->
            <td data-bind="text: $index"></td>
            <!--item serial number from index-->
            <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) {
        /*get current item index*/
        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

<!--item index in array-->
<td data-bind="text: $index"></td>

Serial Number using $index in DOM

<!--item serial number from index-->
<td data-bind="text: $index() + 1"></td>

Item Index Inside the View Model

self.showItemIndex = function (item, event) {
    /*get current item index*/
    var context = ko.contextFor(event.target);
    var index = context.$index();
    alert('The item index: ' + index);
};