alternate row style with $index binding
Asked Answered
M

2

35

I am having trouble getting an alternate-row css class applied to a knockout template with a foreach binding context. I am using knockout 2.1 with the available $index context variable.

This is whats confusing:

My Template

<li class="row" data-bind="css: { alt: $index%2 }"></li>

results in no alt classes being applied, however:

<li class="row" data-bind="text: $index"></li>

works properly and displays the row number.

Marshall answered 27/6, 2012 at 16:48 Comment(0)
M
71

I struggled with this for a couple minutes and found that this question hadn't really been covered since the new binding context variables (like $index)had been introduced in knockout 2.1

The mistake I was making was that I simply forgot that $index itself is an observable, and must be unwrapped if we are using it in an expression in the data-bind attribute. ie,

<li class="row" data-bind="css: { alt: $index%2 }"></li>

should become

<li class="row" data-bind="css: { alt: $index()%2 }"></li>

woops :)

Marshall answered 27/6, 2012 at 16:48 Comment(3)
Was just about to ask and then found your answer! Thanks :)Holophrastic
I was about to go crazy on this one.Sugary
This was frustrating me for a while, thanks for the post! I didn't realise index was an observable.Hrvatska
C
12

Don't do alternate row styling with Javascript, use CSS which is way more efficient :)

https://developer.mozilla.org/en-US/docs/CSS/:nth-child

Castellany answered 2/3, 2013 at 23:39 Comment(2)
While I do agree with you, if you are trying to support < IE9.0, this pseudo-selector is not available. nevertheless, this question is mainly here to help people understand that the $index context variable is itself an observable. cheers :)Marshall
both of these answers have value. depending on context, there are many reasons to use one or the other and it's good to see both of these options here and it makes this question a good resource. this is exactly how stack overflow was intended to work.Humanitarianism

© 2022 - 2024 — McMap. All rights reserved.