Stuff I love: Knockout.js
Categories: JavaScript
Tags: Knockoutjs
I love Knockout.js. If you haven’t heard of it, it’s a JavaScript library for doing complex UI using simple HTML5 bindings to your JavaScript code and takes care of synchronizing the UI with your data automatically. It’s basically the MVVM pattern on the web. I use it almost everyday in my current professional project.
To use it, you create a JavaScript object model that represents the business objects that are a part of your page (for example, let’s say you are making a movie browser and therefore your object model contains an object for Movie with properties like Title, Description, Rating, etc). With this object model, you wrap your properties in what are known as observables. Observables are functions that ensure that when their underlying value changes, any bound UI will automatically change.
Knockout.js also handles the other way – if a UI records a change in input (say, a text box changing in value), the new value gets sent into the observable. This means that KO handles two-way data binding.
The website for Knockout really does a great job of explaining what it does as well as documenting all the features. It’s got some of the best documentation I’ve seen on an open source project. You should check out the tutorials if you are brand new to it.
One of the things that I like best about KO is that it is so extensible. I can write extenders, bindingHandlers, and subscribable functions to really extend the way that it works. This allows me to go beyond the basics. If you haven’t checked it out, Ryan Niemeyer’s Knock Me Out blog is indispensible if you are starting out with KO. Go and read all of it, it’s that good.
Over the next couple of days, I’m going to post some Knockout extenders that I’ve written or used over the past few months that I’ve found to work well.