O'Reilly logo

Knockout.js by Jamie Munro

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 9. The Mapping Plugin

Knockout allows developers to extend the framework by creating plugins, and the original developer has created one called mapping. The purpose of this plugin is to automatically map a standard JavaScript object or JSON data to a new object with each property being an observable object.

This can be extremely useful in several different situations. Where we had been creating objects and manually defining each property as observable, the mapping plugin will do this automatically.

To get started, download the additional JavaScript file. I saved mine into the existing js folder and called it knockout.mapping.js, and that is how these next examples will reference the file.

Map from an Object

In Example 9-1, I convert an example from Chapter 3 that demonstrates the with binding on a single book object. In the original example, a book object is passed to the ViewModel via the constructor. This is then directly assigned to the internal book property and used for displaying with Knockout bindings. However, because it is using the mapping plugin, all of the properties (title, synopsis, and publishedDate) are now being observed.

Example 9-1. Mapping from an object
<!DOCTYPE html>
<html>
<head> 
    <title>Data Binding with KnockoutJS</title>
</head>
<body> 

    <div id="book" data-bind="with: book"> 
        <h1 data-bind="text: title"></h1> 
        <h2>Published on <span data-bind="text: $parent.formatDate(publishedDate())">
        </span></h2> 
        <p data-bind="text: synopsis"></p> 
    </div> 

    

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required