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>
Get Knockout.js now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.