Thursday, February 6, 2014

With binding in KnockoutJS

In this post we will look at yet another important binding in KnockoutJS, the “With” binding. Imagine the situation when you have an object and you want to bind the properties of that object to the controls in the view. The “with” binding comes in handy in these situations.

Let’s take an example to understand this. Consider the following ViewModel for instance,

   1: var ViewModel = function(){
   2:  
   3:     var self = this;
   4:  
   5:     this.WeatherForecast = ko.observable(new Weather('Jabalpur','28'));    
   6:  
   7:     }
   8:  
   9: var Weather = function(city, temperature){
  10:     this.city = ko.observable(city);
  11:     this.temperature = ko.observable(temperature);
  12: }
  13:  
  14: ko.applyBindings(new ViewModel());

We have an observable property WeatherForecast, which contains an object of Weather. Now, if we want to bind the properties city and temperature to the view, the with binding would help us doing that.

Suppose we want to bind the properties city and temperature to two <span> tags. What we do is, we wrap these span tags into a division (you can use section, paragraph or anything of your choice), and data-bind that division with WeatherForecast using “with” binding, and then we can further go and bind the spans inside, with the properties city and temperature. Here is the view:


   1: <html xmlns="http://www.w3.org/1999/xhtml">
   2:  
   3:     <head>
   4:         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   5:         <title>Untitled Document</title>
   6:     </head>
   7:             
   8:         
   9:     <body>
  10:  
  11:         <div data-bind="with: WeatherForecast">
  12:             <span data-bind="text: city"></span>            
  13:             <span data-bind="text: temperature"></span>            
  14:         </div>
  15:          
  16:         <script src="js/knockout 3.0.0.0.js"></script>
  17:         <script src="js/ViewModel.js"></script>
  18:         
  19:  
  20:     </body>
  21: </html>

Hope this post was useful.

Happy Coding!!!

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