What would be the best way to stripe a list with KnockoutJS? The class on the div below should be even or odd depending where it is in the list, and update when adding or removi
There was a topic for this on the KO forums a while back here: https://groups.google.com/d/topic/knockoutjs/cJ2_2QaIJdA/discussion
The solution that I had was a custom binding. There were a couple variations on it, but it basically would look like:
ko.bindingHandlers.stripe = {
update: function(element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()); //creates the dependency
var allBindings = allBindingsAccessor();
var even = allBindings.evenClass;
var odd = allBindings.oddClass;
//update odd rows
$(element).children(":nth-child(odd)").addClass(odd).removeClass(even);
//update even rows
$(element).children(":nth-child(even)").addClass(even).removeClass(odd);;
}
}
and be used like:
Sample here with 3 variations of this binding:
http://jsfiddle.net/rniemeyer/HJ8zJ/