As I understand, $index is available inside a foreach: binding, giving the index of the object... I have a click: binding e.g. c
yes,
<input type="button" data-bind="click: function(data, event) { myClickHandler($index, data, event); }"/>
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()
}
};
It is easier with ES6 code. In my html I have an array of pages
<span data-bind="foreach: pages">
<a data-bind="click: $parent.gotoPage.bind($parent), text: $index()+1">
</a>
</span>
In the view controller class I have the gotoPage method. The first parameter will be the $index of the foreach. Very simple.
class ViewModel {
constructor() {
this.requestedPage = ko.observable(0);
this.pages = ko.observableArray([0,1,2,3]);
}
async run() {
this.message("Running");
}
gotoPage(pageRequested, event) {
this.requestedPage(pageRequested);
this.run();
}
}