KnockoutJS:从JavaScript模板中访问数组中项目的索引

gzo*_*ost 2 indexing ko.observablearray knockout.js

我使用KnockoutJS从数组填充列表:

<div data-bind:"foreach: list">
   <input type="text" data-bind="value: myText" />
</div>

function ViewModel() {
    self.list = ko.observableArray([
        new listItem("sample text")
    ]);
};

function listItem (text) {
    this.myText = text;
};
Run Code Online (Sandbox Code Playgroud)

我可以像这样为我输入的各个实例分配一个id

<input data-bind="attr: { id: $index } ...
Run Code Online (Sandbox Code Playgroud)

如何从listItem函数中访问此索引?我希望能够做类似的事情

function listItem (text) {
    this.myText = text;
    this.index = $index;
};
Run Code Online (Sandbox Code Playgroud)

为了进一步处理使用它.

RP *_*yer 14

您可以创建一个自定义绑定,将您的属性设置为索引,它看起来像:

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

这假设您正在处理数组中的对象.您会像以下一样使用它:

<ul data-bind="foreach: items">
    <li data-bind="setIndex: 'myIndex', text: name"></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

因此,这会$index使用您指定的属性名称将observable 复制到您的对象上.示例:http://jsfiddle.net/rniemeyer/zGmcg/

您可以在绑定之外执行此操作的另一种方法(这是我以前用过的方法$index)是订阅对observableArray的更改并每次重新填充索引.

以下是observableArray的扩展可能如下所示:

//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;
};
Run Code Online (Sandbox Code Playgroud)

然后你会像以下一样使用它:

this.myItems = ko.observableArray().indexed('myIndexProp');
Run Code Online (Sandbox Code Playgroud)

以下是一个示例:http://jsfiddle.net/rniemeyer/bQD2C/