KnockoutJS If Not Binding

In the last article we saw how if binding adds or removes markup from a webpage depending upon a certain conditions. In this article we shall study yet another type of control flow binding i.e. KnockoutJS if not binding. This binding is similar to if binding but has a reverse affect. Basically if not binding specifies whether a section of HTML markup along with its data-binding attributes shall be displayed or not. The decision of if not binding is based on expression that returns true-like or false-like output. If the expression evaluates to false, the markup section is displayed and vice versa.

It is important to differentiate here between the if not binding and the visible binding. The visible binding maintained the html markup on the screen and the associated data-bind attributes remained on the webpage, visible binding only toggled its visibility. However, if and if not binding adds or removes the markup from page totally along with their associated data-bind attributes. Let’s have a look at our first example to see KnockoutJS if not binding in action.

If Not binding Example!

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    

    <label><input type="checkbox" data-bind="checked: Male" /> Male</label>
 
<div data-bind="ifnot: Male">Student is not a Male.</div>
    
    
<script>
    function StudentModel() {
    this.Male = true;
}

ko.applyBindings(new StudentModel());
    
</script>
    
</body>
</html>

Download the code Try the code

In the above code we have check box and a div in html view section. In the javascript view model section we create model named StudentModel with one parameter i.e. Male. The value assigned to Male is false by default. Now come back to view section, here we set the “checked” attribute of the check box to the value of Male parameter which is true. Therefore, when you open the page in the browser, you shall see Male checkbox unchecked. Secondly, the div contains an if not binding which says that display the div only if Male parameter is not set to true. When you open the page, the text inside the div shall be visible since Male doesnt contain true.

Now in the javaScript view model, change the value of Male parameter to true and open the page. You shall male checkbox checked and the contents of the div removed from the page.

Model-View-ViewModel (MVVM)

KnockoutJS is based on MVVM pattern. It is an architectural pattern used to design software applications. John Gossman, a Microsoft architect, built the model in 2005. The biggest benefit of the model is that it separates the business logic from graphical user interface. Derived from ViewModel Controller Pattern, this very model makes it very easy to manage and represent data by allowing you to handle underlying data in a certain way. You can also represent abstract forms of actions and View’s state via ViewModel in Model-View-ViewModel.

The ViewModel and Model classes do not know that the view classes exist and the vice versa. Similarly, Model has no idea that both the View and ViewModel exist.

View:

View is usually created through a markup language. It is actually a Graphical User Interface which helps you represent data. It works on the principle of data binding to connect properties of a ViewModel. The data bind concept itself is indirectly connected to model data. If there is any change in a ViewModel, you need to change the View as well. The binding automatically reflects all the changes made in ViewModel in View.

Model:

It is simply a business object or domain data. It is the Model which actually holds all the real time data. However, it has nothing to do with behaviors. They are mostly implemented in business logic layer.

ViewModel:

ViewModel is the main processing unit of the MVVM and holds dynamic data. Data from both View and Model integrates at ViewModel through an implicit binder which makes them communicate with each other. This binder contains command binding and declarative data. The binder is also responsible for synchronizing ViewModel and View. Changes occurring in both the View and ViewModel reflect in each other. The existence of automatic 2 way binding is the most important aspect of this model.

KnockoutJS Application Structure

Developers mostly use KnockoutJS when they are working on single page applications. It helps you reduce server round trips because you have single page website that has the ability to retrieve all the dynamic data users need.
KnockoutJS makes it very for users to bind domain data with HTML because it is a server side JavaScript library. It implements a specific function commonly known as “Model-View-ViewModel (MVVM). The special features of this framework are the Observables attribute which keeps all the data synced. This article explains knockoutJS application structure.

View:

View is the first element of the KnockoutJS. It is actually a user interface you create using HTML and CSS.
This framework also helps you bind data model to HTML DOM elements. Its unique data-bind concept offers 2 different ways to bind data between View and ViewModel. This simply means that the data model reflects all the changes made in User Interface and vice versa. You can also create self-updating User Interfaces using this framework.

ViewModel:

It is nothing more than a JavaScript object. It represents data with the help of necessary functions and properties it contains. Knockout JavaScript uses HTML’s data-bind concept to combine both View and ViewModel. It helps change HTML without disturbing ViewModel. The framework uses Observables to control automatic data refresh between ViewModel and HTML.

The framework bonds data model to HTML DOM elements to synchronize data. Firstly, it uses the data-bind concept to sync data followed by using Observables to refresh both these components. The synchronization of data makes dependency tracking automatic without the need of any extra coding. You can directly connect the underlying data with your display as well.
For behaviors specific to different application, you can also create your own custom bindings. This enables you to transfer all the data to HTML the way you want.

Model:

It is simply data available on serve related to the application domain. KnockoutJS helps you manipulate this data by sending and receiving requests from ViewModel.
There are many types of permanent storages such as cookies and database where you can store the data. This framework has nothing to do with the type of storage. It is up to you to create communication channel between the KnockoutJS and the data. Mostly, you will load data using Ajax call. In this article we studied knockoutJS application structure, in the next article we shall see MVVM architecture in detail.

KnockoutJS If Binding

In the last article we started control flow bindings. We saw what foreach binding is and how to use it. In this article we shall study yet another type of control flow binding i.e. KnockoutJS if binding. This binding is similar to if statement (if you familiar with any programming language). Basically if binding specifies whether a section of HTML markup along with its data-binding attributes shall be displayed or not. The decision of if binding is based on expression that returns true-like or false-like output. If the expression evaluates to true, the markup section is displayed and vice versa.

It is important to differentiate here between the if binding and the visible binding. The visible binding maintained the html markup on the screen and the associated data-bind attributes remained on the webpage, visible binding only toggled its visibility. However, if binding adds or removes the markup from page totally along with their associated data-bind attributes. Let’s have a look at our first example to see KnockoutJS if binding in action.

If binding Example!

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    

    <label><input type="checkbox" data-bind="checked: Male" /> Male</label>
 
<div data-bind="if: Male">Student is a Male.</div>
    
    
<script>
    function StudentModel() {
    this.Male = false;
}

ko.applyBindings(new StudentModel());
    
</script>
    
</body>
</html>

Download the code Try the code

In the above code we have check box and a div in html view section. In the javascript view model section we create model named StudentModel with one parameter i.e. Male. The value assigned to Male is true by default. Now come back to view section, here we set the “checked” attribute of the check box to the value of Male parameter which is true. Therefore, when you open the page in the browser, you shall see Male checkbox checked. Secondly, the div contains an if binding which says that display the div only if Male parameter is set to true. When you open the page, the text inside the div shall be visible.

Now in the javaScript view model, change the value of Male parameter to false and open the page. You shall male checkbox unchecked and the contents of the div removed from the page.

knockoutJS foreach Bindings

In the last few articles, we covered most of the appearance and text bindings. In this article and the next few we shall study control flow bindings. Control flow bindings, as the name suggests control the flow of code execution. In this article we shall study knockoutJS foreach bindings.

KnockoutJS foreach bindings basically repeat html markup according to the number of elements in an array. In each markup repetition you can access the corresponding item in the array. Another very exciting prospect of foreach binding is that if you have an observable array, adding or removing elements from the array shall automatically reflect in the markup. Adding an element will add markup for the element and removing an element shall automatically remove markup.

Usually knockoutJS foreach bindings are used to display list of elements. Take a look at the following example where we simply display the names and ages of some random students in some imaginary school.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    
    <table>
        <thead>
            <tr><th>Student Name</th><th>Student Age</th></tr>
        </thead>
        <tbody data-bind="foreach: students">
            <tr>
                <td data-bind="text: studentName"></td>
                <td data-bind="text: studentAge"></td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript">
        ko.applyBindings({
            students: [
                { studentName: 'Mark', studentAge: 21 },
                { studentName: 'Gren', studentAge: 19 },
                { studentName: 'John', studentAge: 23 },
                { studentName: 'Ygritte', studentAge: 18 },
                { studentName: 'Hodor', studentAge: 40 }
            ]
        });
    </script>
    
</body>
</html>

Download the code Try the code

Take a careful look at the above code. Check JavaScript view model section first. Here we declare an array named students. Each item in an array is an object written in JSON format. Each object has studentName and studentAge parameter. There are 5 objects in total.

Now come to the html view section. Here we have created a table to show the studentName and studentAge parameter from the objects in students array. Notice that the foreach binding is used with the “tbody” tag which means tha whatever is inside this tag shall be repeated the number of times the elements in the students array. Also, during each iteration the values for studentName and studentAge parameters shall be displayed within the

tags.

It is important to note here that if you remove or add more student objects in the students array in view model, the information of the newly added students will automatically be added into the table and vice versa.

KnockoutJS Attr Bindings

In the previous articles we covered all most all of different types of appearance related bindings. We saw visible, text, html, css and style bindings. In this article we shall study the last type of appearance related bindings i.e. KnockoutJS attr bindings. Basically this type of binding sets the attribute value of any HTML DOM element. Typically you add url to href tag or image path to source tag using attr binding. The attr basically stands for attribute. Take a look at the following example to see knockoutJS attr bindings in action.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>


</head>
    
<body>
   <img data-bind="attr: { src: ImageAddress}" />
    

   <script>
      function ImageModel() {
this.ImageAddress= ko.observable('http://images.freeimages.com/images/previews/caf/communications-tower-1309311.jpg')
                                                                                                                             
      }
      var sm = new ImageModel();
      ko.applyBindings(sm);
   </script>
</body>
</html>

Download the code Try the code

Take a careful look at the above code. In the HTML view section, we have an image tag. Using the attr binding, the source attribute of the image tag has been assigned an ImageAddress parameter of the ImageModel. The ImageAddress parameter contains source of the image. In the JavaScript view model, we have an ImageModel which has an observable ImageAddress which contains some random image source,.

Parameter passed to the attribute binding is in the form of JavaScript object notation where parameter is the name of the attribute and the value is the value assigned to the parameter.

Modifying ‘Href’ of a Link

In the following example we shall explain how we can use parameter from the view model and assign its value to the href tag of a link. Take a look at this code:

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>


</head>
    
<body>
   <a data-bind="attr: { href: LinkAddress}">
       
       link to google
    </a>
    

   <script>
      function ImageModel() {
this.LinkAddress= ko.observable('www.google.com');
                                                                                                                             
      }
      var sm = new ImageModel();
      ko.applyBindings(sm);
   </script>
</body>
</html>

Download the code Try the code

In the above code, in the html view, we have an anchor tag. The attribute binding binds he href attribute of the anchor tag to the LinkAddress parameter of the ImageModel. Now if you open the above page in browser, you shall see a link that points towards google.com.

In the next article, we shall start studying control flow binding. Happy Coding!

knockoutJS Style Binding

In the last article, we saw how we can use css binding to add or remove css classes from HTML DOM elements. What if instead of adding or removing predefined css classes, we want to add our own custom styles to HTML DOM elements? KnockoutJS has provisions for that as well. KnockoutJS style binding allow us to add our custom styles to DOM elements. We can add custom styles to DOM elements directly or if some function or expression returns true. In this example, we shall specify both approaches.

Adding Custom Styles Via Expressions

In the following example we shall change the text color of the div to yellow if the value of the StudentAge parameter of the StudentModel class is greater than 0 else the color of the text will be red. Take a look at the following code.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

 <style>
      .warningMessage {
      color: red;
      font-weight: bold;
      }
   </style>
</head>
<body>
   <div data-bind="style: { color : StudentAge() <= 0 ? 'red' : 'yellow'}">
      Age should be greater than 0.
   </div>

   <script>
      function StudentModel() {
         this.StudentAge = ko.observable(1);
      }
      var sm = new StudentModel();
      ko.applyBindings(sm);
   </script>
</body>
</html>

Download the code Try the code

Take a look at the above code. Here in the div section we use data-bind attribute to apply style binding. Inside the style binding we apply the condition which if true makes the color of the text red and if false changes the color of the text to yellow. The condition is that StudentAge of the StudentModel should have value zero or less than that. If you come down and see the script you will find that the value of the StudentAge parameter is 1, therefore if you open the webpage, you shall see a message written in yellow.

Adding Styles Directly

You can also directly add styles if you want without any expression. Take a look the following piece of code.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

 <style>
      .warningMessage {
      color: red;
      font-weight: bold;
      }
   </style>
</head>
<body>
   <div data-bind="style: { color : 'brown'}">
      Age should be greater than 0.
   </div>

   <script>
      function StudentModel() {
         this.StudentAge = ko.observable(1);
      }
      var sm = new StudentModel();
      ko.applyBindings(sm);
   </script>
</body>
</html>

Download the code Try the code

In the above code, we removed the expression and directly assign the color brown to “color” property of the style. Now, if you open the webpage you shall see that the text inside the div always appear in the brown color. In this article we studied knockoutJS style binding, in the next article we shall see last type of control and appearance bindings i.e. attribute binding.

KnockoutJS CSS Bindings

Till now, we have covered visible binding, text binding and html bindings. Now is the time to study yet another extremely important type of binding i.e. knockoutJS CSS bindings. This type of binding basically adds or remove a class from you cascading style sheet to an element. CSS bindings are particularly helpful when you want to change the style of an element depending upon a certain condition. Let’s have a look at at a simple example of knockoutJS CSS bindings.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

 <style>
      .warningMessage {
      color: red;
      font-weight: bold;
      }
   </style>
</head>
<body>
   <div data-bind="css: { warningMessage : StudentAge() <= 0 }">
      Age should be greater than 0.
   </div>

   <script>
      function StudentModel() {
         this.StudentAge = ko.observable(0);
      }
      var sm = new StudentModel();
      ko.applyBindings(sm);
   </script>
</body>
</html>

Download the code Try the code

Take a look at the above code. First go to the header section, here we have defined an internal style. We have specify a class which changes the color of the text to bold and change its color. The name of the class is the “warningMessage”. Now take a look at the html view. Here inside the div we use data-bind attribute to set the css of the div to “warningMessage” if the StudentAge parameter of the StudentModel is greater than 0. Notice the synax for css binding. It is similar to JavaScript object notation where the first parameter is the name object and second parameter is its value. The second parameter in this case is the expression. If this expression returns true, the “warningMessage” class will be applied to the div.

Now come to the JavaScript section of the code, here we create a StudentModel which has a parameter StudentName with value 0. If you change the value of this parameter to anything greater than 0, the color of the text in the div shall change to default.

Apart from passing the expression which returns to true or false, you can directly pass the true-like or false-like value. For instance in the following example StudentMale parameter is set to true. This parameter is then used for CSS binding which changes color and weight of the text to bold. Take a look at the following example.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

 <style>
      .warningMessage {
      color: red;
      font-weight: bold;
      }
   </style>
</head>
<body>
   <div data-bind="css: { warningMessage : StudentMale }">
      Age should be greater than 0.
   </div>

   <script>
      function StudentModel() {
    
          this.StudentMale = ko.observable(true);
      }
      var sm = new StudentModel();
      ko.applyBindings(sm);
   </script>
</body>
</html>

Download the code Try the code

KnockoutJS Text & HTML Bindings

In the last tutorial we saw how visible binding control the appearance of an html element. In this article we shall see two more types of bindings i.e. knockoutJS text & html bindings. We have previously used the former binding, however in this article we shall study its nitty-gritty. So, let the fun begin!

KnockoutJS Text Bindings

Simply put, the text binding changes the value for the text attribute of the tag. Typically text binding updates the em, span or paragraph tags. Behind the scenes, the text binding replaces the default content of the html element with text node having value passed as parameter. If the parameter is observable then any change in the value of the parameter automatically updates the text. Take a look at the following example to see text binding in action.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    

   <p>Student Name: <input data-bind="value: StudentName" /></p>
   <p>Student  <strong data-bind="text: StudentName"></strong> obtained 90% marks.</p>

   <script>

   function StudentModel() {
       this.StudentName = ko.observable("");
   }

  
   ko.applyBindings(new StudentModel());
   </script>
    
</body>
</html>

Download the code Try the code

Let’s start from the paragraph tag at the top. Inside the paragraph we have the input element. The data-bind attribute here binds the value entered in this input tag to the “StudentName” parameter of the StudentModel view model. Next again data-bind binds the value of the StudentName parameter to “text” attribute of the strong tag inside the paragraph. Now if you enter any name in the text box and press the enter key. The corresponding value in the paragraph shall be updated immediately. This is because we have used “observable” with StudentName.

KnockoutJS HTML Binding

The html binding as the name suggests updates the content of any html DOM element and replaces it with html specified by the parameter in JavaScript view model. If the parameter is an observable, updating the parameter’s value updates the corresponding html. Take a look at the following example.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    
<div data-bind="html: StudentName">  </div>
 
   <script>

   function StudentModel() {
       this.StudentName = ko.observable("<h1>The name of the student</h1>");
   }


   ko.applyBindings(new StudentModel());
         
   </script>
    
</body>
</html>

Download the code Try the code

In the above example, some html has been assigned to the StudentName parameter of the StudentModel view model in the JavaScript section. In the html view the html of the div is associated with StudentName, therefore div shows an h1 element with some text as specified by StudentName parameter. This article explains knockoutJS text & html bindings. In the next article we shall see CSS bindings.

KnockoutJS Visible Binding

In this article and some of our upcoming articles we shall study different types of bindings that KnockoutJS supports. We shall start with KnockoutJS visible binding in this article. Basically visible binding makes the associated DOM element visible or hidden depending upon the value set in it.

It is best to explain KnockoutJS visible binding with the help of an example. Take a look at the following piece of code. The code is explained in the section that follows.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    
<div data-bind="visible: StudentName">
    This text will only be visible if StudentName of the StudentModel holds true-like value.
</div>
 
   <script>

   function StudentModel() {
       this.StudentName = ko.observable(true);
   }

   ko.applyBindings(new StudentModel());
         
   </script>
    
</body>
</html>

Download the code Try the code

In the above code we have a div with some random text. KnockoutJS visible binding is used to set the hide or display property of the div via “StudentName” attribute of the StudentMode of the JavaScript. By default, the StudentName is set set as observable with value true. Therefore the div is visible by default. However, if you change the value of the StudentName observable to false, you shall see that the div shall not appear.

How KnockoutJS Visible Binding Works

Basically visible binding sets the element.style.display property to none if it contains some false-like value which can be false, a value less than zero etc. Similarly, setting visible to true-like value e.g true or something greater than 0 removes style.display.none from the element thus making it visible.

Apart from passing true-like or false-like values for visible bindings, you can also use functions and expressions directly with visible binding. For instance in the following example we have an array inside the StudentModel with zero items. Next we add one item into this array. In the HTML view, the visible binding is assigned the result of the expression that checks if the items in the array are greater than zero, which in our case is true. Therefore the text in the div will be visible. However, if there were no items in the array, the div text would have been hidden. Take a look at the code.


Download the code Try the code

In the next article we shall see other binding types. Keep visiting this site! Happy coding!

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .