I populate a list from an array using 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;
};
I can assign an id to the individual instances of my input like so
<input data-bind="attr: { id: $index } ...
How do I access this index from within my listItem function? I want to be able to do something like
function listItem (text) {
this.myText = text;
this.index = $index;
};
in order to use this for further processing.
You could create a custom binding that sets your property to the index, it would look something like:
This assumes that you are dealing with objects in your array. You would use it like:
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:
You would then use it like:
Here is a sample: http://jsfiddle.net/rniemeyer/bQD2C/