indexing - knockout JS : Access index of item in array from within the JavaScript template

标签 indexing knockout.js ko.observablearray

我使用 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;
};

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

<input data-bind="attr: { id: $index } ...

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

function listItem (text) {
    this.myText = text;
    this.index = $index;
};

以便将其用于进一步处理。

最佳答案

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

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

这假定您正在处理数组中的对象。你会像这样使用它:

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

因此,这会将可观察到的 $index 复制到具有您指定的属性名称的对象上。示例:http://jsfiddle.net/rniemeyer/zGmcg/

您可以在绑定(bind)之外执行此操作的另一种方法(这是我在 $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;
};

然后您可以像这样使用它:

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

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

关于indexing - knockout JS : Access index of item in array from within the JavaScript template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12229578/

相关文章:

arrays - 有没有办法访问向量中的索引

当选择控件的源/选项更改时,JQuery 触发事件

javascript - KnockoutJS observableArray : group data in foreach

javascript - knockout.js 不对可观察数组进行排序

sql - 我如何强制 Postgres 使用特定的索引?

Python 列表问题

sql - 两列上的唯一索引是否意味着每列都有一个索引?

javascript - knockoutjs 中的滑动 Action 绑定(bind)

knockout.js - Knockout JS - 使用静态类名和数据绑定(bind)类名

javascript - knockout : How to add one observableArray to another?