Playing With KnockoutJS
by Justin Michalicek on Dec. 18, 2013, 2:39 a.m. UTCI've been trying to build up my front end dev skills a bit lately and get to know some of the front end JavaScript frameworks out there better, or in some cases, at all. The most interesting thing I've been working with lately is KnockoutJS. The short description of what it does is that rather than hand writing all of the event bindings using jQuery or whatever you like, you add a bit of extra markup in the HTML and a few simple, mostly single line variable declarations/assignments in your JavaScript. Knockout then handles the event binding, updating displayed values in the HTML as JavaScript variable values change, etc.
They have a tutorial site which walks you through several examples of the sorts of things you'll commonly do with Knockout. It starts with basic binding of displayed data to hard set variables, or observables. By the end it has examples of binding data to ajax requests and all the sorts of things you need to do for many dynamic sites these days.
I have found that in some cases the documentation is a bit lacking, though. For instance the checked binding describes how to bind checkboxes to an observableArray(). It hints at what happens here, but doesn't really spell it out, which caused me some confusion. The value of the checkbox input gets added to the array when checked. If a value is added to the array, any checkboxes with that value which are bound to the observableArray will become checked. An example of where this becomes troublesome and not initially clear is with Django forms. The checkbox inputs are created and all just have a value of "yes" when checked by default. So you check one, the value "yes" gets added to the obserableArray, and then the rest automatically check as well. The solution is to manually assign a different value to each checkbox using something like Django Widget Tweaks.
I also needed to bind to a form's submit event and make an ajax submission. This is straightforward enough, but I wanted to do it the pure Knockout way as described here. I needed to access the event object to get at some of the data and use it in my $.ajax() call. Unfortunately those docs don't describe how to do that. They do link to a different page for a different binding which does give an example of how to get the event object, but it didn't seem to work for submit. In the end I used the event binding, which is just a slightly longer-winded way to bind to the submit event, which does provide a clear way to get the event object.
Overall I like KnockoutJS and will probably continue to use it. I think once I know all of the ins and outs I will be able to write my front end code more quickly and have cleaner code than I end up generating with just jQuery.