KnockoutJS - with Binding


Advertisements

This binding is used to bind the child elements of an object in the specified object's context. This binding can also be nested with other type of bindings such as if and foreach.

Syntax

with: <binding-object>

Parameters

  • Pass the object which you want to use as context for binding child elements as the parameter. Child elements will not be shown if the object or expression passed is evaluated to be null or undefined.

  • The expression will be re-evaluated, if the parameter provided is an observable one. Correspondingly, the child elements will be re-processed based on the refreshed context result.

Example

Let us take a look at the following example which demonstrates the use of with binding.

<!DOCTYPE html>
   <head>
      <title>KnockoutJS with binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <h1 data-bind = "text: siteName"> </h1>
      
      <table border = "1">
         <thead>
            <th>Course Name</th><th>Fees</th><th> Start Date</th>
         </thead>
         
         <tbody data-bind = "with: courses ">
            <tr>
               <td><span data-bind = "text: courseName"></span></td>
               <td><span data-bind = "text: Fees"></span></td>
               <td><span data-bind = "text: startDate"> </span></td>
            </tr>
         </tbody>
      </table>

      <script type="text/javascript">
         function AppViewModel() {
            self = this;
            self.siteName = ko.observable( 'TutorialsPoint');
            self.courses = ko.observable ({
               courseName:  'Microsoft .Net', 
               Fees: 20000, startDate: '20-Mar-2016'
            });
         };
         
         var vm = new AppViewModel();
         ko.applyBindings(vm);
      </script>
      
   </body>
</html>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above code in with-bind.htm file.

  • Open this HTML file in a browser.

Observations

Container-less with

There might be a situation when it is not possible to place data-binding inside a DOM element. Essential binding can still be performed with the help of container-less syntax based on the comment tags as shown in the following code.

<ul>
   <li>Course Info</li>
   <!-- ko with: currentClasses -->
      ...
   <!-- /ko -->
   <!-- ko with: plannedClasses -->
      ...
   <!-- /ko -->
</ul>

The <!--ko--> and <!--/ko--> works as start and end markers making it a virtual syntax and binds the data as if it is a real container.

knockoutjs_declarative_bindings.htm
Advertisements