Book Image

Mastering KnockoutJS

By : Timothy Moran
Book Image

Mastering KnockoutJS

By: Timothy Moran

Overview of this book

Table of Contents (16 chapters)
Mastering KnockoutJS
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Knockout Mapping


The Knockout Mapping plugin is the answer to projects that want to bind against their server's AJAX responses without manually writing the JavaScript classes in order to convert them into observables. The mapping plugin will convert JavaScript objects or JSON strings into objects with observable properties:

var mappedViewmodel = ko.mapping.fromJS({
   name: 'Timothy Moran',
   age: 24
});
ko.applyBindings(mappedViewmodel);

For JSON, take a look at the following code:

var serverResponse = "{"name":"Timothy Moran","age":24}";
var mappedViewmodel = ko.mapping.fromJSON(serverResponse);
ko.applyBindings(mappedViewmodel);

The mapping plugin handles arrays by converting them into observableArrays. It also creates a copy of objects, allowing a complete object graph from the server to be converted into an observable object.

Updates against viewmodels created with the mapping plugin can be performed by passing the viewmodel as the second parameter to fromJS or fromJSON:

ko.mapping.fromJS...