KnockoutJS Quick Q&A

Introduction

This is the first in a short series about KnockoutJS - a very useful frontend development library that is well worth getting to know - it's simple to implement, has nowhere near the learning curve of say AngularJS, but is an extremely powerful tool to have in your kit!

If you have an interview coming up for a front-end dev position, and need to brush up a bit on the top topics for KnockoutJS, then this is the article for you - read on!...

KnockoutJS is being used more frequently in projects as a lightweight tool to assist quick development in the browser, especially where ViewModels and arrays are involved. Knockout is quick to learn and while it doesn’t have anywhere near the functionality of, say, AngularJS, it does provide a powerful mechanism for working with data and vastly reduces the amount of code needed to implement a robust, modern, client-side solution. Unlike Angular, which encompasses many concepts including data-binding, integrated testing, view management, etc., Knockout only promises one thing – highly efficient data-binding, but it does this extremely well indeed. Due to its increasing popularity, questions about it are being asked at interviews – this is a list of some of the more common questions I have seen discussed in preparing interviews. If you understand these concepts, you will be well on your way to putting together a solid Knockout solution.

What is KnockoutJS ?

KnockoutJS is a JavaScript library that helps developers create modern, rich user interfaces with a clean underlying data model. Whenever you have a user-interface that needs to update when an underlying data model updates, then KnockoutJS is a useful tool that could be used. Steve Sanderson who works at Microsoft designed KnockoutJS. It is an open source project, and is used to power the front-end of the beautifully designed Azure control interface (wow!).

Designing large SPAs with KO:

Why is KnockoutJS useful ?

Knockout can dramatically reduce the amount of code needed to synchronize a data model and user interface controls. It is fast, cross browser compatible, and not reliant on any other libraries. It is lightweight (< 20kb after compression) and can be easily integrated with most web applications without any major architectural update.

Describe a Knockout ViewModel

A Knockout ViewModel looks very much like a basic class that is created in JavaScript as a function. It is declared as a variable, and can have members and methods.

How do you activate a Knockout Model ?

To activate a model, we call the key method ‘i’, passing in the name of the model to bind to as a parameter. ‘ko.applyBindings(MyNewKOModel)’.

Can you have multiple Knockout models on one page, and if so, how would you use them ?

Yes, Knockout can bind to multiple models at one time. The key to keeping the different models isolated is to put any mark-up in separate div containers, named with a unique ID, and to call the key ‘applyBindings’ method for each model, passing in the viewModel as the first parameter, and the matching div ID as the second parameter.

  1. ‘ko.applyBindings(MyFirstKOModel, document.getElementByID(‘firstDiv’))’.
  2. ‘ko.applyBindings(MySecondKOModel document.getElementByID(‘secondDiv’))’.

What is two way data binding ?

Knockout uses the “data-*” tags to create a live dynamic link between a browser UI control, and a member or method inside a data ViewModel. If you have a data model with a field ‘FirstName’ and an edit box linked using the data-bind attribute to ‘FirstName’, then anytime the data model changes (for example programmatically), that change immediately shows in the edit box, and any time a user makes a change to the FirstName in the edit box, the underlying data in the field ‘FirstName’ is changed.

What is an observable ?

In knockout, declaring a member as observable means when its value changes any other object watching the member gets notified it has been changed. This simple concept allows two-way data-binding to be implemented.

What is an observable array and give an example of where they are useful

Simply, it is an array of observable objects. Observable arrays can be when handling object collections such as the individual items in a shopping cart for example.

What is a computed observable ?

This is a special type of function that is dependent on one or more observable to work. For example, when the one or more observable value computed is linked to changes, the computed observable gets called. The classic example is a computable called ‘Full Name’ which observes and combines ‘first name’ and ‘last name’ to make ‘Full name’.

How do you search or sort an observable array ?

You can search and sort using a ‘ko.Computed’ function. The computed function could implement an ‘arrayFilter’ call from the Knockout utils library to search, and a relevant compare (on string, number, date) for the sort. In all cases, the computed function filters out what it doesn’t want and returns data accordingly.

How do you prepare a Knockout object for data transfer ?

Data can be serialized to JSON using ko.toJSON(viewModel), and to a simple JavaScript object using ko.toJS(viewModel).

What is the purpose of the mapping plugin ?

When loading data into a viewModel, if it is complex with nested arrays, it can be troublesome to unwrap all members manually. The mapping plugin assists with this and allows you to tell Knockout how to handle complex data like structures with nested arrays by providing pattern functions.

What is a binding, what are the binding types, and what are they used for ?

A binding is a html mark-up attribute that is added to an html element to create a link between the html control element and a knockout object. It takes the format ‘data-bind:<binding-type:value>’. There are binding types to assist with objects like control text, visibility and CSS styles, and other types to assist with form fields such as value, submit, event, etc. Bindings might be used to display the title label of a page, the visibility of a checkbox, and control the data entry in form field.

How can you control flow with bindings ?

When you have an array of items in a Knockout viewModel, you can tell your mark-up to iterate through them using the data-bind ‘for-each’ for example.

Give a benefit of using Knockout form binding

Normal functionality we might implement around form fields such as getting/setting the field value, hooking events, etc. can be carried out using ‘form data-bind’. A benefit of doing this is that we allow control of the form to be tied to the data model and its rules.

How do you delete an item from a Knockout array ?

Use the remove or removeAll methods, passing in the item you want to match for deletion.

How would you flag an item deleted and why is this useful ?

In cases where you want to manage an array of existing data, for example browser-side, and inform the server of both additions, changes and deletions, you can flag an array item using the ‘destroy’ or ‘destroyAll’ method. This creates a dirty record that is flagged “_destroy” and can be easily identified server-side for handling in the data repository.

How do you call a Knockout method using data bind concept ?

Knockout allows us to use the data-bind concept to hook into user control object events such as ‘click’. To do this, we use a ‘data-bind’ with the method we want to call as the click parameter ‘data-bind=click: callSomeMethod”’.

What is a use of templates in Knockout and how are they coded ?

Knockout allows us to use the data-bind concept to hook into user control object events such as ‘click’. To do this, Templates can provide different blocks of mark-up to be used for different view renderings, for example, to show mark-up with a required ‘State’ field for a US address, and a required ‘Town’ field for say a UK address. Mark-up for templates can be implemented using an external template view-engine, or by implementing the html inside a pseudo JavaScript block.

Name two context properties in Knockout and explain their use

When working with arrays, the $index property returns the index of the current context item in the array. When working with nested objects, the $parent property allows us to examine the parent of an object, for example a customer may have many orders, an order may have many line items. The order is the parent of the line item, the customer is the parent of the order.

And that's the core of what you need to know - if they ask anything else, ask if they are offering you the job, your time is precious.

Up Next
    Ebook Download
    View all
    Learn
    View all