Sunday, December 22, 2013

Data Manipulation – KnockoutJS

The core concept of every application you use is to play with data. Saving and Reading data are the two major tasks an application should be well versed into. In this post we will be looking at how to make api calls and map them to our View using Knockout JS.

The project setup would be same as previous posts. In addition to Knockout a J-Query library is also added for making the Ajax call to the server api.

The Sample

image

Time to time we have to go to the market and buy a few things. This sample on which we are going to work on, will helps in remembering those things. It makes the Api call and get the items that are to be purchased and display them onto the UI, as simple as that. We can then mark the items that we have purchased and thereby keep the record on the items which are yet not bought.

View

Our view would simply be a list displaying items and a label counting them.

   1: <!DOCTYPE html 
   2:     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   3:         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:  
   5: <html xmlns="http://www.w3.org/1999/xhtml">
   6:  
   7: <head>
   8: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   9: <title>Untitled Document</title>
  10: </head>       
  11:     
  12: <body>
  13:  
  14:      <div>
  15:     
  16:          <ul data-bind="foreach: items">
  17:              <li>
  18:                 <input type="checkbox" data-bind="checked: isPurchased"/>
  19:                 <span data-bind="text: name"></span>
  20:             </li>
  21:          </ul>
  22:          
  23:          You have not yet purchased 
  24:                 <b data-bind="text: notPurchasedItem().length">&nbsp;</b> item(s).
  25:      
  26:      </div>
  27:     
  28:     <script src="~/Scripts/jquery-1.7.1.min.js"></script>
  29:     <script src="~/Scripts/Custom/knockout%203.0.0.0.js"></script>
  30:     <script src="~/Scripts/Custom/ViewModel.js"></script>
  31:  
  32: </body>
  33: </html>

If you have read my previous posts on KnockoutJS, above HTML for view would not bother you. It contains few simple bindings with the properties and Prototypes defined in the view model.

The ViewModel

Following is the over all code of the ViewModel.


   1: var ViewModel = function () {
   2:  
   3:     var self = this;
   4:         
   5:     self.itemToBring = ko.observable();
   6:     self.items = ko.observableArray();
   7:     
   8:     self.notPurchasedItem = ko.computed(function(){
   9:         return ko.utils.arrayFilter(self.items(), 
  10:                 function(item) { return !item.isPurchased() });
  11:     });
  12:         
  13:     $.getJSON("http://localhost:3213/api/values", {    
  14:     tagmode: "any",
  15:     format: "json"
  16:     }).done(function (args) {
  17:         for (var i = 0; i < args.length; i++) {
  18:             self.items.push(new Item(args[i]));
  19:         }
  20:     });    
  21:     
  22: }
  23:  
  24: var Item = function(newItem){
  25:     this.name = ko.observable(newItem.name);
  26:     this.isPurchased = ko.observable(newItem.isPurchased);
  27: }
  28:  
  29: ko.applyBindings(new ViewModel());

The only line of code that we are interested in is $.getJSON(). This method makes the call to the Api’s Url specified and get the JSON. Once it’s done downloading JSON, it executes the call back method and push the values that it receives, to the observableArray(). 

The URL http://localhost:3213/api/values is the location where I’ve hosted my API. The JavaScript usually will not allow making the call to the url pointing the external source. So you need to host this application in the same place where you have your API hosted. A MVC4 WEBAPI project is the best way to do so.

Happy Reading!!

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