Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout.js How to access $index in handler function

Tags:

knockout.js

As I understand, $index is available inside a foreach: binding, giving the index of the object... I have a click: binding e.g. click:foo , I need to to access $index inside foo.

Is there a way?

like image 851
Tom Avatar asked Oct 24 '12 17:10

Tom


1 Answers

Rather than hacking around it through a function within your binding, you just need to get the binding context. As long as you have access to the DOM element associated with the binding, you can get the binding context and all its properties using the ko.contextFor() function.

The event object you get in your handler gives you access to the node through the target property. Grab the context using that.

var viewModel = {
    foo: function (data, event) {
        var context = ko.contextFor(event.target);
        // do stuff with context.$index()
    }
};
like image 130
Jeff Mercado Avatar answered Oct 24 '22 06:10

Jeff Mercado