Thoughts on KnockoutJS

If you haven’t had a chance to use or read about KnockoutJS, do so!

I had wanted to try it out in a project for a while and the opportunity presented itself a few months back so I jumped on it.  It was at first a little confusing to work with because it was my first exposure to the concept of MVVM.

MVVM

For those not yet familiar, Knockout is self described as a Model View ViewModel (MVVM) framework. It took me a little bit to wrap my head around what exactly a ViewModel is. The ViewModel is kind of like a controller, but reversed. It handles interaction between the View and the Model (probably why it is called a ViewModel), but it doesn’t handle things like picking which View file to render like a traditional Controller might do in the MVC pattern. The best example I found when reading about it was from Addy Osmani.

“Rather than our models being aware of a user’s view of the date (e.g 04/07/2012 @ 5:00pm), where it would be necessary to convert the address to it’s display format, our model simply holds the raw format of the data.”

So the ViewModel is responsible for interpreting the Model data and sending it off to the View. On page load the View loads in and anywhere that data is bound it asks the ViewModel what goes there. The ViewModel in turns interacts with the Model and passes that data to the View.

So what blew me away?

Perhaps it was just the wow factor, but I was in awe by the concept of observables and their uses within a web application. By creating an observable variable and binding that to a text input, the value of the variable is then updates in real time if the user changes it. This allows you to build an application that in real time validates and sanitizes the data in the “big picture” rather than the typical validation/sanitizing of a specific field one at a time. For example, you build an application that validates zipcode based on the state. If a user moves they would come in and first update their state, if they attempted to save without updating the zipcode it may save because the data “was” valid with the old state. Using Knockout you can set up rules and checks so that once the state changes it would also check the zipcode and any associated data to ensure it is valid. Depending on the field type you could use the computed field type instead of observable, or you can create a function that subscribes to the change of a field.

self.stateField = ko.computed(function(){
// combine fields and validate address 
// to make sure it is good to go
});

self.stateField.subscribe(function(value) {
// do what you need to to check if other 
// stuff is accurate now that state has changed
});

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>