knockout.js How to access $index in handler functi

2019-02-04 07:13发布

问题:

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?

回答1:

yes,

<input type="button" data-bind="click: function(data, event) { myClickHandler($index, data, event); }"/>


回答2:

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


回答3:

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


标签: knockout.js