KnockoutJS: Access index of item in array from within the JavaScript template

后端 未结 1 1687
遇见更好的自我
遇见更好的自我 2021-01-03 11:45

I populate a list from an array using KnockoutJS:

相关标签:
1条回答
  • 2021-01-03 12:25

    You could create a custom binding that sets your property to the index, it would look something like:

    ko.bindingHandlers.setIndex = {
        init: function(element, valueAccessor, allBindings, data, context) {
            var prop = valueAccessor();
            data[prop] = context.$index;
        }        
    };
    

    This assumes that you are dealing with objects in your array. You would use it like:

    <ul data-bind="foreach: items">
        <li data-bind="setIndex: 'myIndex', text: name"></li>
    </ul>
    

    So, this copies the $index observable on to your object with the property name that you specify. Sample: http://jsfiddle.net/rniemeyer/zGmcg/

    Another way that you can do this outside of bindings (this is how I used to do it before $index) is to subscribe to changes to the observableArray and repopulate an index each time.

    Here is what an extension to an observableArray might look like:

    //track an index on items in an observableArray
    ko.observableArray.fn.indexed = function(prop) {
        prop = prop || 'index';
       //whenever the array changes, make one loop to update the index on each
       this.subscribe(function(newValue) {
           if (newValue) {
               var item;
               for (var i = 0, j = newValue.length; i < j; i++) {
                   item = newValue[i];
                   if (!ko.isObservable(item[prop])) {
                      item[prop] = ko.observable();
                   }
                   item[prop](i);      
               }
           }   
       }); 
    
       //initialize the index
       this.valueHasMutated(); 
       return this;
    };
    

    You would then use it like:

    this.myItems = ko.observableArray().indexed('myIndexProp');
    

    Here is a sample: http://jsfiddle.net/rniemeyer/bQD2C/

    0 讨论(0)
提交回复
热议问题