Array Index of

204 views
Skip to first unread message

derek johnston

unread,
Jul 29, 2011, 7:54:34 AM7/29/11
to KnockoutJS
Hi,

I have observerable array that is used with a template on page.

On the page I have a new button that inserts into the array

viewModelTrackerViewModelForm.posts.unshift(post);

i also have a publish button on each item on the page and if clicked
and the item is the first item in the array I want to create another
item and insert into the array.

I only want to do this if the current item array index is 0

Is there a way to get the index of an item?

thanks

derek

rpn

unread,
Jul 29, 2011, 8:00:56 AM7/29/11
to knock...@googlegroups.com
If you have access to the parent and it is an observableArray, you can just do: myObservableArray.indexOf(theItem);.  If it is not an observableArray, then you can loop on it yourself or use the utility function ko.utils.arrayIndexOf of like:   ko.utils.arrayIndexOf(myArray, theItem)

I suspect that maybe it is inconvenient for you to access the parent at the time that you want to know the index.  Here was a recent solution to always maintain an index by subscribing to the observableArray.  

Here was the explanation:

If you don't want to use {{each}}, because you don't want your entire template to re-render constantly, then you could put an "index" property on your individual items.  Rather than make it a dependentObservable on each item where re-evaluating would require looping through the array and finding your own index, I would probably do a manual subscription on the observableArray and make one loop through the items and update the "index" property.  Might look like this:

//attach index to items whenever array changes
viewModel.tasks.subscribe(function({
    var tasks this.tasks();
    for (var 0tasks.lengthji++{
       var task tasks[i];
        if (!task.index{
           task.index ko.observable(i);  
        else {
           task.index(i);   
        }
    }
}viewModel);

You could obviously call the observable whatever you want, if index might cause a conflict.  The nice part about this is that you don't really have to mess with your item definition at all, as this index is just managed completely from this subscription.  You would want to set up this subscription prior to adding any items to your array.  Sample here:  http://jsfiddle.net/rniemeyer/CXBFN/
Reply all
Reply to author
Forward
0 new messages