Having problems with user-responsive, interactive UI's? Sick of confusing and complicated js-code to handle your UI? Knockout is the solution.

I first stumbled upon the knockout-library during the implementation of a UI with lots of interactive features, like updating a field if another field changes, displaying areas only if a certain option is set, … Simple actions are very easy to implement with jQuery, but if your UI gets bigger, your js-Code gets more and more confusing handling all the special cases occuring on your UI. Knockout works with data-models defined in your js-code. The code keeps clean and simple to understand and the library let you create bindings between your models and your HTML-Code.

Simple example: Making a div visible if a certain checkbox is checked

With jQuery you have to show the div if the checkbox is checked and hide the div if it's unchecked.

With Knockout you can create a model with a param for the checked-option and bind this param to your html-elements with the “data-bind” - attribute.

Creating the viewModel

var viewModel = {
showDiv: ko.observable()
};

Apply bindings (activate knockout)

ko.applyBindings(viewModel);

Binding the showDiv-attribute to your input

<input type=”checkbox” data-bind=”checked: showDiv” />

Displaying the div only if your checkbox is checked

<div data-bind=”visible: showDiv”>
Some content
</div>

These bindings work like a charm, i'm fascinated. Long story short, use this library for your UI's, invest some time to understand it's functionality and it will spend you a lot of time in the future, trust me!

There are a lot of tutorials on the website which are very nice, interactive and also very simple to understand, give it a go!

knockoutjs.com


comments powered by Disqus