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.

<<< KnockoutJS If BindingKnockoutJS Click Binding >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .