I need to name the <div>'s in a KnockoutJS template according to the position that they appear in the list for a Jquery plugin like so:
<div id="item1">...</div>
<div id="item2">...</div>
<div id="item3">...</div>
Is there a way to bind to the index of the item in the array using KnockoutJS?
It would be a shame if I had to add this data to the select on the database using ROWINDEX.
update: KO now supports a
$indexcontext variable that you can use within aforeach(ortemplatewithforeachparam). Docs: http://knockoutjs.com/documentation/binding-context.htmlIf you are okay with using jQuery Templates
{{each}}, then something like this will work:If you had to use the
foreachoption, then something like this would work:Edit: these days I prefer to create a subscription to my observableArray that only has to take one pass through the array and create/set an index observable on the item. Like:
Sample here: http://jsfiddle.net/rniemeyer/CXBFN/
or you can take this idea and extend observableArrays to provide an
indexedfunction that would allow you to set this up just by callingmyObservableArray.indexed().Here is a sample: http://jsfiddle.net/rniemeyer/nEgqY/