Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternate row style with $index binding

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.

like image 977
Leland Richardson Avatar asked Jun 27 '12 16:06

Leland Richardson


1 Answers

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 :)

like image 92
Leland Richardson Avatar answered Sep 28 '22 09:09

Leland Richardson