knockout.js How to access $index in handler function

后端 未结 3 959
温柔的废话
温柔的废话 2020-12-30 01:45

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

相关标签:
3条回答
  • 2020-12-30 02:17

    yes,

    <input type="button" data-bind="click: function(data, event) { myClickHandler($index, data, event); }"/>
    
    0 讨论(0)
  • 2020-12-30 02:28

    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()
        }
    };
    
    0 讨论(0)
  • 2020-12-30 02:30

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题