Knockout.js Interview Questions and Answers

Knockout is a standalone JavaScript implementation of the Model-View-View Model pattern with templates. The underlying principles are therefore:

A clear separation between domain data, view components and data to be displayed

The presence of a clearly defined layer of specialized code to manage the relationships between the view components

The latter leverages the native event management features of the JavaScript language. These features streamline and simplify the specification of complex relationships between view components, which in turn make the display more responsive and the user experience richer.

KnockoutJS was developed and is maintained as an open source project by Steve Sanderson, a Microsoft employee on July 5, 2010. As the author said, “It continues exactly as-is, and will evolve in whatever direction I and its user community wish to take it”, and stressed, “This isn’t a Microsoft product. KO is an abbreviation used for Knockout JS. KO supports all mainstream browsers – IE 6+, Firefox 3.5+, Chrome, Opera, Safari (desktop/mobile).

Knockout is a JavaScript implementation of the Model-View-ViewModel software pattern (MVVM). It allows us to bind HTML elements against any data model. It provides a simple two-way data binding mechanism between your data model and UI means any changes to data model are automatically reflected in the DOM (UI) and any changes to the DOM are automatically reflected to the data model. Any time you have sections of UI that update dynamically (Ex: changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

The Knockout.js provides a simple and convenient way to manage this kind of complex, data-driven interfaces. One can create self-updating UIs for JavaScript objects. It is pure JavaScript Library and works with any web framework. It’s not a replacement of JQuery but can work as a supplement providing smart features. Instead of manually tracking, each element of the HTML page rely on the affected data and will automatically updated the DOM when any changes to the data model occurs. KnockoutJS library file is very small and lightweight. KnockoutJS is independent of any other framework. It is compatible with other client or server-side technologies. Most important of all KnockoutJS is open source and hence free for use.

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 the two-way data-binding to be implemented.

MVVM (Model View ViewModel) is an architectural design pattern originated by Microsoft and mainly created for WPF/Silverlight applications. But we can use this Web application too with ASP.NET. MVVM is a specific implementation targeted at UI development platform which supports event driven programming for WPF/Silverlight. It respects the programming principle “Separation of Concern”. It completely separates GUI Rendering logic from Application Logic (Data Logic/Business Logic). MVVM was developed by Microsoft Architect John Gossman in 2005.

The Model-View-ViewModel pattern can be used on all XAML platforms. Its intent is to provide a clean separation of concerns between the user interface controls and their logic. There are

Model: The model in MVVM is an implementation of the application’s domain model that includes a data model along with business and validation logic. The key to remember with the model is that it holds the information, but not behaviors or services that manipulate the information. It is not responsible for formatting text to look pretty on the screen, or fetching a list of items from a remote server (in fact, in that list, each item would most likely be a model of its own).

View: The view role in this pattern is to observe (or subscribe to) a ViewModel observable to get data in order to update UI elements accordingly. The view is responsible for defining the structure, layout, and appearance of what the user sees on the screen. Ideally, the view is defined purely with XAML, with a limited code-behind that does not contain business logic.

View Model: The view model acts as an intermediary between the view and the model, and is responsible for handling the view logic. Typically, the view model interacts with the model by invoking methods in the model classes. The view model then provides data from the model in a form that the view can easily use. The view model retrieves data from the model and then makes the data available to the view, and may reformat the data in some way that makes it simpler for the view to handle. The view model also exposes methods, commands, and other points that help maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events in the view itself.

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”’.

Knockout’s declarative binding system provides a concise and powerful way to link data to the UI. It’s generally easy and obvious to bind to simple data properties or to use a single binding. For more complex bindings, it helps to better understand the behavior and syntax of Knockout’s binding system.

A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko.applyBindings(viewModel). Then, each time you use a control flow binding such as with or foreach, that creates a child binding context that refers to the nested view model data.

The foreach binding duplicates a section of markup for each entry in an array and binds each copy of that markup to the corresponding array item. This is especially useful for rendering lists or tables.

If you want to detect and respond to changes on one object, you’d use observables. If you want to detect and respond to changes of a collection of things, use an observable Array. This is useful in many scenarios where you’re displaying or editing multiple values and need repeated sections of UI to appear and disappear as items are added and removed. The KnockoutJS Observable sort () method sorts all items in the array. By default, items are sorted in an ascending order. For sorting an array in a descending order, use reverse () method on sorted array.

Computed Observable is a function which is dependent on one or more Observables and automatically updates whenever it’s underlying Observables (dependencies) change. If the Computed Observable is based on a simple property (not an observable property) then a change in property will not trigger a change in Computed Observable. A change in Computed Observable is triggered if any of the observable properties that it is based on is changed.

KnockoutJs automatically tracks the dependencies when the values get updated. It has a single object called dependency tracker (ko.dependencyDetection) which acts as an intermediate between the two parties for subscribing the dependencies.

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.

Template is a set of DOM elements which can be used repetitively. Templating makes it easy to build complex applications due to its property of minimizing duplication of DOM elements.

There are 2 ways of creating templates.

Native templating: this method supports the control flow bindings such as foreach, with, and if. These bindings capture HTML markup existing in the element and use it as template for random items. No external library is required for this templating.

String-based templating: KO connects to the third party engine to pass ViewModel values into it and injects the resulting markup into the document. For example, JQuery.tmpl and Underscore Engine.