In this section, we will talk about the knockout.mapping
plugin. This plugin allows you to map some plain JavaScript object to a Knockout.js ViewModel with observable properties. It can be very useful when you want to receive some data from the server in the JSON format and show it to the user via declarative bindings.
For better understanding of the mapping concept, let's consider an example with manual mapping of JSON data to a ViewModel object. We will take a very abridged version of the library model from the previous chapters. Suppose the model contains only two properties: LibraryName
and AmountOfBooks
.
Let's define a corresponding ViewModel:
var libraryViewModel = { LibraryName: ko.observable(), AmountOfBooks: ko.observable() }
Next, we add a View:
The library <span data-bind="text: LibraryName"> contains <span data-bind="text: AmountOfBooks"> books.
Then, we should receive data from the server. Suppose we have a special...