I just finished my first non-trivial web app that leverages Knockout, a framework that helps you build better javascript front-end applications. While Knockout isn’t nearly as popular as Backbone.js is, I think it serves a different purpose, even though they’re typically lumped together. There’s a great set of answers on Backbone vs Knockout on StackOverflow about this, but the fact that a post like that exists proves the point.

For me, I picked it because:

  • I only wanted to add functionality to a single page of my application, rather than build an entire single-page app.
  • The data-bind attributes are a little ugly, but expressive at least. So I think it’s easy to read the HTML and understand what’s going on without even really looking at the javascript.
  • Accomplishing most things in Knockout requires less code than Backbone.

I wanted to improve the performance of a search page. Essentially the functionality allows users to search for products from a number of vendors based on the location of that vendor. So, for example, “Show me all instructors offering tennis lessons in the Boston area.” The results page would then be broken down by instructor, and a list of their offerings in that category.

Here’s what I implemented in Knockout:

  • Search results load on demand via jQuery json calls to the server.
  • I aggressively cache data using local storage. In this case I used store.js from Marcus Westin to simplify browser compatibility.
  • With the caching, I intercept updates to the UI by hooking into the Knockout subscribe and only loading data via ajax that isn’t already in the cache.
  • Local storage also saves the current state of the page if you’ve already saved items in your cart. We don’t have a need to save cart information on the server, so local storage made sense. If you clear your cart, it will also clear the cache next time you visit the page to make sure you get the most updated data.
  • Data is submitted via a hidden form field, similar to what Steven Sanderson lays out in his post.
  • All written in CoffeeScript, of course.

Two things worth pointing out that helped me:

  1. First, Ryan Niemeyer’s blog Knock Me Out has a great set of posts on Knockout. Start with 10 things to know about KnockoutJS on day one, but explore from there.
  2. Second, surprisingly enough was reading the Knockout source code on Github. I think javascript is incredibly hard to follow because of it’s prototype nature, but this helped me figure out some additional things that just aren’t covered in the Knockout documentation.