ChrisS
ChrisS

Reputation: 2595

Knockout.js - Conditional value based on item position in the model data

I am trying to figure out how to get access to the current index that is being bound. I don't care about the model itself, I want to execute a function if the current observable array item is at index X. Is this possible?

I have a fiddle going for a visual reference at http://jsfiddle.net/cmschick/hyHQW/2/.

The problem I am trying to solve is I need the column widths to match. Right now I have two tables but I would like to just have one, that would automatically take care of the widths but then my problem is how do I add the text "Allergies" on row 0, cell 0 and the text "Adverse reactions" on row X cell 0...

Hopefully there is a trick that I'm not considering. I really don't want to create the markup on the server side. Any pointers would be much appreciated.

Thanks.

Upvotes: 1

Views: 487

Answers (2)

Mark Robinson
Mark Robinson

Reputation: 13278

Regarding:

Right now I have two tables but I would like to just have one, that would automatically take care of the widths but then my problem is how do I add the text "Allergies" on row 0, cell 0 and the text "Adverse reactions" on row X cell 0...

... if you use nested templates - a main template to render the general person info and table structure which then calls one to render the allergies and one to render the adverse reactions, you may find you don't need to go to such lengths and it may simplify your issues. I had similar issues and it certainly worked well for me!

Upvotes: 0

RP Niemeyer
RP Niemeyer

Reputation: 114792

Normally, I would suggest something like: https://groups.google.com/d/topic/knockoutjs/LbfktgENJPk/discussion to maintain an index on the items in an observableArray.

It looks like you are returning arrays from dependentObservables, so that won't quite do it.

Another thought would when you are building your result in your dependentObservables, keep track of an index whenever you add a row and when you actually push the row to the result, push an object like: { data: row, index: currentIndex }. Then bind against data.x or do a data-bind="with: data"

Upvotes: 2

Related Questions