Getting Started with Knockout js


Warning: Illegal string offset 'filter' in /var/sites/t/theproactiveprogrammer.com/public_html/wp-includes/taxonomy.php on line 1409

I like to keep a list of new, interesting or important technologies which I would like to learn more about. Currently my list is dominated by javascript-related libraries and frameworks, including the following:

Although this list is slightly daunting, I am excited by the prospect of learning more about some or all of these technologies. Programming in javascript is fun, with no need to compile, huge flexibility and nice debugging tools available in the browser. Add to this the growing demand for javascript ninjas with experience of single page applications, and we have a more than adequate motive for learning more about such things.

This week I have been looking at knockout.js. The knockout team have created a great set of tutorials at learn.knockoutjs.com, which have been my main source of learning.

This blog post will hopefully help to solidify my learning, bearing in mind the view that the best method for learning something is to teach it.

Knockout is based on the MVVM pattern, and therefore its separation approach will be familiar to those who have experience working with other MV* patterns. It is similar to many other javascript libraries in that its key benefit is data binding. This allows us to bind html elements to model properties, where our model consists of one or more javascript objects. As a result of this binding, updating the model can automatically update the view, and vice versa. This can greatly reduce the amount of code required for vanilla client-side functionality.

The knockout website doesn’t provide its own cdn, but, remembering that it is always best to load javascript libraries from a cdn, I found one available at cdnjs.com.

Building a Model

Let’s start then by building a simple model which, in order to be slightly topical, will represent some of the teams taking part in the world cup in Brazil.

We’ll create constructor functions for Team and Model classes, and use them to create some objects.

This kind of data would typically be retrieved from the server, via an ajax call.

This is all standard javascript except for the last line, where we instruct knockout to bind to the model we have created:

Displaying a Table

Now to display this information in a table. Knockout allows us to easily bind a javascript array to an html table, or any other form of repeating html. We will represent our team data in a table.

Here we can see how knockout uses the data-bind attribute to bind the teams array in our model to the table. In the tbody element we use the foreach binding, to instruct knockout to iterate through our array of teams and generate the specified html (a table row) for each item. We can also see the data-bind attribute is used on each td element, with the text binding, to instruct knockout to display the value of each corresponding property as text within that cell.

Adding a little CSS for the table, we get the following.

Click Binding

Now let’s change the team names into anchor links, which when clicked will raise an alert message showing the team’s fixtures. First we add a function, showFixtures, to our Team class.

This uses the knockout utility function arrayForEach (similar to the jquery .each() function) to iterate through the team’s fixtures, and constructs a string which is displayed in an alert box. Now all we need to do is add an anchor element to our table html, using the click binding to bind to our new ‘showFixtures’ function.

And here is our jsfiddle now:

Observables

We will now add a points property to our Team class, and add buttons which update the property. We will also add a points column to our table, which will be automatically updated with our model.

In knockout, a property which causes the view to be automatically updated, and vice versa, must be declared as an observable.

So rather than declaring our points property in the traditional way:

…we need to declare it like this:

When we declare a property as an observable we need to include brackets when getting or setting the property, for example:

Returning to our example, having added our points property as an observable, we will now add three functions which will update this property – addWin(), addDraw() and resetPoints().

Next we update our table html to include a new points column, and three buttons corresponding to our three new functions.

This gives us our desired result.

Submit Binding

Finally, we will add a simple form which will allow us to add new teams to our table. We will add observable properties to our Model class, which will represent the new text fields into which we will enter data for the new teams.

By making these properties observable, we remove the need to write javascript to retrieve data directly from our input fields. Instead we can just bind our form fields to these properties:

Note how we have also used the data-bind attribute, with the submit binding, on the form element, to bind the form’s submit behaviour to a function on our model named ‘addTeam’, so let’s go ahead and add this function to the Model class.

..giving us our final result.

Summary

This example shows us how knockout provides standard javascript features requiring little or no actual javascript code. It helps us to maintain a healthy separation between our view and our model, and allows us to write better code and to meet the customer’s requirements more quickly, which has to be a good thing. As we have seen, we can quickly introduce standard web functionality without ever hitting the server. In future posts I will be looking at some of the other javascript libraries listed above.

I have only really scratched the surface of knockout here. To learn more, go to the knockout website.

Share Button