Live search with knockout.js
Knockout.js is an interesting take on building rich web applications. While I was initially turned off by the MVVM approach of embedding bindings in the view, it has grown on me after playing around with it for a few days. I look forward to experimenting with it on a larger application.
My first experimentation with knockout is to implement live search. Here is a demo of searching for beers by name:
How to build it —————
To start with, we just want to display our list of beers. Once we get that done, then we can start implementing the search. I used a hard-coded list for this example, but this could easily be the result of an API request.
We need to tell knockout about these beers so we can bind them to the view.
Displaying this list of beers is simple. We create our markup for the list, and use knockout’s template binding.
Now we should be able see our list of beers. Next let’s implement the search functionality, starting with an input field to search with.
The data-bind attribute tells Knockout that we want to bind the value of this input field to a variable called query, and we want to update that value on keyup. We need to set up query as an observable attribute.
Whenever the query attribute is changed, we want to perform our search and update our list of beers, so we subscribe to updates on query
and call a search function.
Our search function begins by removing all the beers from the array observed by knockout, then loops through our list of beers and does a simple search, adding each beer back to the knockout array if it matches, which in turn updates it in the view.
View the source on the demo to see all of the code in context.