Archive for January, 2012

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/

KnockoutJS ‘Addons’, etc…

Posted: January 22, 2012 in Uncategorized

This is not intended to be a full post – just wanted to highlight a few links to add ons to the javascript knockoutjs library I’ve been using on some recent projects:

Observable Dictionary :  github source  gist of example

Protected Observable: blog post with sample code  gist of example

KO ‘Datagrid’ : link to google group post  github source  samples

I’ll update this with more links – it would be great to have a knockoutjs community

Steve Michelotti has a KnockoutJs course of Pluralsight and an example of building a custom binding

Also just to add – I have an example of KnockoutJS with NodeJs on my github here with a few simple tests using jasmine-node for some specs, and QUnit showing some Knockoutjs test scenarios.