A common scenario with Javascript is toggling a set of elements based on the selected element add applying, removing css classes. You’ll see this on menu items, etc… and in my case where we want to have styled ‘button’s instead of a radio list.
An example of this might be handling the selection of the button and then applying a class and removing any other classes, for example:
$(‘.year_item’).bind(‘click’, function(){
$(“.year_Item”).removeClass(“selected_year”);
$(event.currentTarget).addClass(“selected_year”);
});
In my first attempt at such a toggle with knockoutjs, I followed a similiar route – calling back to my viewmodel :
setYear: function (year, event) {
$(“.year_Item”).removeClass(“selected_year”);
$(event.currentTarget).addClass(“selected_year”);
myViewModel.year(year);
}
The binding in the html looks like this:
<ul data-bind=”foreach: years”>
<li><input data-bind=”text: $data, click: $parent.setYear” type=’button’/></li>
</ul>
This works fine. However, I can do better – since KnockoutJs supports setting the CSS class on binding.
ie. <div data-bind=
"css: { profitWarning: currentProfit() < 0 }"
>
So let’s take this example and show how we can effectively toggle the CSS class based upon the value of the binding – using our example above:
<ul class=”bigButtons” data-bind=”foreach: years”>
<li><input data-bind=”text: $data, click: $parent.year, css:{selected_year: $parent.year() === $data}” type=’button’/></li>
</ul>
That is it. No more function required in the viewmodel. To understand what happens here is to understand the $parent.year click event. Basically in KnockoutJs 2.0 by default $parent.year takes the $data property as a parameter. The year binding is set, which in turn triggers the css selection on all the items reevaluating if it should have that CSS appended.
This has proved to be very terse and valuable in our UI.
Edit: I’ve put an example out on jsFiddle: http://jsfiddle.net/sgentile/pRC4c/
This was exactly what I was looking for, thank you very much 😀
I love to see an example of this. Would you mind showing us the complete code?
Thanks!
Sure – here is a jsFiddle example: http://jsfiddle.net/sgentile/pRC4c/
Struggled with this for a while. Should have thought of this 🙂
Thanks