Click here to Skip to main content
Click here to Skip to main content

Using $index in Knockout.js

, 16 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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);
};

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DiponRoy

Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.141022.1 | Last Updated 16 Jul 2014
Article Copyright 2014 by DiponRoy
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid