How to Add Knockout Computed Observables With the Knockout Mapping Plugin

The knockout Mapping Plugin is a great way to save time, and write less code when creating view models in knockout. When I first started using knockout I was hesitant to use the mapping plugin because I was afraid that I would lose some control over the customization of my view model. But after staring at the documentation for a while, and then tinkering in jsFiddle, I found that it is possible to have full control over the model that the mapping plugin generates.

The following example demonstrates how to manually insert knockout computed observables into an observableArray that is generated with the Knockout Mapping Plugin.


Knockout.js released by Steve Sanderson in summer of 2010. Although Steve works for Microsoft the decision to release knockout.js as an open source project was right.

It is a standalone javascript library relying on MVVM and Observable patterns. The key principles of knockout.js are:

* 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

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.

Knockout.js includes the following features:

* Declarative bindings
* Automatic UI refresh (when the data model’s state changes, the UI updates automatically)
* Dependency tracking
* Templating (using a native template engine although other templating engines can be used

In this example, two text boxes are bound to observable variables on a data model. The “full name” display is bound to a dependent observable, whose value is computed in terms of the observables. When either text box is edited, the “full name” display is automatically updated, with no explicit event handling.

HTML code snippet:

   <p>First name: <input data-bind="value: firstName" /></p>
   <p>Last name: <input data-bind="value: lastName" /></p>
   <h2>Hello, <span data-bind="text: fullName"> </span>!</h2>

Javascript code snippet:

function ViewModel() {
    this.firstName = ko.observable("John");
    this.lastName = ko.observable("Smith");
    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);
ko.applyBindings(new ViewModel());