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?
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()
}
};
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