Sunday, February 9, 2014

Working with JSON in KnockoutJS

JSON or JavaScript Object Notation is a format used to transmit the information from one place to another. By one place to another, means from one system to another, and is very popular now a days.

Knockout not only makes the client side developer’s life easy rather provide a rich framework to make the client side development more interactive then ever before. Even a client side developer now a days, need to send JSON information every now and then. They could go through many ways available like using ajax, JQuery etc, on the other hand, knockout also provide a more easy and rather sophisticated way to work with JSON. In the following post we will see on how we can work with JSON using Knockout.

Consider the following ViewModel:

   1: var ViewModel = function(){
   2:  
   3:     var self = this;
   4:  
   5:     self.ideals = ko.observableArray();    
   6:  
   7:     self.ideals.push(new idealPersons("Dhananjay Kumar","JavaScript"));
   8:  
   9:     self.getData = function(){
  10:         //Log the Value of the ViewModel
  11:     }
  12:  
  13: }
  14:  
  15: var idealPersons = function(name, expertise){
  16:     this.name = name;    
  17:     this.expertise = expertise;
  18: }
  19:  
  20: ko.applyBindings(new ViewModel());

Knockout offers two methods to help working with JSON.

ko.JS Method

It converts the ViewModel into an Object Graph, it substitute each observable with its current value and creates a plain copy of it. Replacing the comment “Log the Value of the ViewModel” with this code

console.log(ko.toJS(this));

would result in following output:

image

ko.JSON Method

This method converts the ViewModel into JSON. It internally uses ko.JS to first create the object graph of the ViewModel and then uses the inbuilt javascript’s method to convert that object graph into JSON. Changing ko.JS to ko.JSON in the ViewModel, the result would be like:

image

Which is a JSON output ofcourse. This is how you can user knockout to work with JSON.

I hope this post would be useful.

Share this post

0 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© 2013 Neelesh Vishwakarma
Posts RSS Comments RSS
Back to top