KnockoutJS - SPLessons

Knockout.js JSON And View Model Interoperabilities

Home > Lesson > Chapter 11
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Knockout.js JSON And View Model Interoperabilities

Knockout.js JSON And View Model Interoperabilities

shape Introduction

This chapter demonstrates about the Knockout.js JSON And View Model Interoperabilities which always allow client side interactivity and all web applications also need to exchange the data and following are the concepts are covered in this chapter.
  • Saving JSON Data
  • Converting viewModel to Plain JSON

Saving JSON Data

shape Description

Knockout permits user to execute sophisticated customer side interactivity, however all web applications likewise need to interchange the data with the server, or if nothing else to serialize the data for local storage. The most advantageous approach to exchange or store information is in JSON format is the majority of Ajax applications utilize today. Knockout doesn’t force user to use anybody specific technique to load or save data. you'll be able to use no matter mechanism could be a convenient suitable your chosen server-side technology. the foremost commonly-used method is jQuery’s ajax helper methods, like getJSON, post, and ajax. you'll be able to fetch knowledge from the server. [code] $.getJSON("/some/url", function(data) { // Now use this data to update your view models, // and Knockout will update your UI automatically }) [/code] In which user can also send the data to the server is as shown in below code. [code] var data = /* Your data in JSON format - see below */; $.post("/some/url", data, function(returnedData) { // This callback is executed if the post was successful }) [/code] Or, if you don’t wish to use jQuery, a user will use the other mechanism for loading or saving JSON data. So, all Knockout has to assist you to do is:
  • For saving, get the read model knowledge into a straightforward JSON format, therefore, user will send it exploitation one among the higher than techniques.
  • For loading, update the read model exploitation knowledge which user received exploitation one among the higher than techniques.

Converting viewModel to Plain JSON

shape Description

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: 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]

Summary

shape Key Points

  • Knockout doesn’t force user to use anybody specific technique to load or save data.
  • Direct approach is the simplest and most versatile resolution.
  • JSON format is the majority of Ajax applications utilize today.