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
$index
context variable that you can use within aforeach
(ortemplate
withforeach
param). 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
foreach
option, 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
indexed
function that would allow you to set this up just by callingmyObservableArray.indexed()
.Here is a sample: http://jsfiddle.net/rniemeyer/nEgqY/
This is much easier with Knockout 2.1.0 and above:
No fancy scripts necessary.
A word of caution:
attr: { id : 'item' + $index }
will NOT work. Since$index
is a function itself, failing to add the parentheses will cause your id to be the concatenation of 'item' and the entire function definition!Had the same problem but with a dependantObservable as source for the foreach template, alas the ko.utils.arrayIndexOf didn't work...
Solution: created a function that recreated the array returned by the dependantObservable and simply used the js indexOf function with the Item:
Et voilà, the expected index in the jQuery tpl.