User read models are JavaScript objects, thus in an exceedingly sense, user will simply set up them as JSON victimization any standard JSON serializer, like JSON.stringify (a native perform in modern browsers), or the json2.js library. However, your read models in all probability contain observables, computed observables, and observable arrays, which are enforced as JavaScript functions and so won’t always set up cleanly while not additional work on your behalf.
To make it straightforward to set up read model information, as well as observables and also the like, Knockout includes 2 helper functions:
- ko.toJS
this clones your read model’s object graph, work for every discernible the present price of that observable, thus you get an apparent copy that contains solely your information and no Knockout-related artifacts.
- ko.toJSON
which produces a JSON string representing your read model’s information. Internally, it simply calls blow.toJS on your read model, and so uses the browser’s native JSON serializer on the result. Note: for this to figure on older browsers that haven't any native JSON serializer (e.g., that is seven or earlier), you want to conjointly reference the json2.js library.
The code below demonstrates the view model as follows.
[code]
var viewModel = {
firstName : ko.observable("Bert"),
lastName : ko.observable("Smith"),
pets : ko.observableArray(["Cat", "Dog", "Fish"]),
type : "Customer"
};
viewModel.hasALotOfPets = ko.computed(function() {
return this.pets().length > 2
}, viewModel)
[/code]
Which contains a combination of observables, computed observables, evident arrays, and plain values. you'll be able to convert it to a JSON string appropriate for causation to the server victimisation blow.toJSON as follows.
[code]
var jsonData = ko.toJSON(viewModel);
// Result: jsonData is now a string equal to the following value
// '{"firstName":"Bert","lastName":"Smith","pets":["Cat","Dog","Fish"],"type":"Customer","hasALotOfPets":true}'
[/code]
Updating View Model Data using JSON
In several scenarios, this direct approach is the simplest and most versatile resolution. Of course, as user can update the properties on read model, Knockout can pay attention of change the visible UI to match it.
However, several developers a lot of highly to use a more conventions-based approach to change their read models exploitation incoming information while not manually writing a line of code for each property to be updated. Which will be helpful if read models have several properties, or deeply nested information structures, as a result of it will greatly cut back the number of manual mapping code user would like to write as shown in below code.
[code]
// Load and parse the JSON
var someJSON = /* Omitted: fetch it from the server however you want */;
var parsed = JSON.parse(someJSON);
// Update view model properties
viewModel.firstName(parsed.firstName);
viewModel.pets(parsed.pets);
[/code]