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.
- 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:
- 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.