KnockoutJS - Visible Binding



As the name specifies, this binding causes the associated DOM element to be visible or hidden based on the value passed in the binding.

Syntax

visible: <binding-condition>

Parameters

  • When the parameter transforms into false-like value (such as boolean false, or 0, or null, or undefined), then the binding sets display:none for yourElement.style.display making it hidden. This is given more priority over any existing styles in CSS.

  • When the parameter transforms into true-like value (such as boolean true,or nonnull object or array ), the binding removes yourElement.style.display value, making it visible.

  • If this is an observable property, then the binding will update visibility every time the property changes. Else, it will just set the visibility once.

  • The parameter value can also be JavaScript function or arbitrary JavaScript expression that returns a Boolean. DOM element is made visible or hidden based on the output.

Example

Let us take a look at the following example.

<!DOCTYPE html>
   <head>
      <title>KnockoutJS Visible Binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" 
         type = "text/javascript"></script>
   </head>

   <body>
      <div data-bind = "visible: showMe">
         You are seeing this line because showMe function is set to true.
      </div>

      <script>
         function AppViewModel() {
            this.showMe = ko.observable(false);  // hidden initially
         }

         var vm = new AppViewModel();
         ko.applyBindings(vm);                  //  shown now
         vm.showMe(true);
      </script>

   </body>
</html>

Output

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

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

  • Open this HTML file in a browser.

knockoutjs_declarative_bindings.htm
Advertisements