08 October, 2011

Learn Something New: Knockout JS

First in my “Learn Something New” series is Knockout, a javascript MVVM framework.

Knockout is beautifully simplistic. You define a ViewModel, bind it to your UI, and away it goes keeping the two in sync. It really is beautiful stuff for a javascript heavy UI.

To learn my way with Knockout, I decided to create a basic twitter search client in javascript. The twitter search API is a great resource for quickly adding data to a “hello world”-esque application. I am bound to revisit it later.

Now let’s get a few more details out of the way, you can see the site up and running at http://twitches.apphb.com/ and you can get the source code at https://github.com/csainty/Twitches

The interesting code lives in the only View and the Javascript.
The page basically consists of a textbox to enter a search term, a button to run the search and a UL that is bound to the results. There is some other fluff in there, but this is the core functionality.

Here is a trimmed down version of the javascript to highlight the main features.

So we define our viewModel, give it an observable value for the search string, an observable array for the results and a function to perform the search.
We apply these bindings and that is it for the javascript. The actual binding to the UI happens in the UI, using HTML5 data attributes.

Here are the key elements from the HTML, as you can see we bind the UI with a jQuery.tmpl template, and wire up the value for the textbox and the click event for the button.
It really is as simple as that.

I highly recommend the tutorials at the Knockout website, they have created a wonderful live tutorial that takes you through each step of the process.

Tools and Services Used

No comments: