KnockoutJS - uniqueName Binding


Advertisements


This binding is used to generate a unique name for a DOM element. If the DOM element did not have a name attribute, this binding gives it one and sets it to some unique string value.

You won’t need to use this often. It’s only useful in a few rare cases, for example −

  • jQuery Validation currently will only validate elements that have names. To use this with a Knockout UI, it’s sometimes necessary to apply the uniqueName binding to avoid confusing jQuery Validation.

  • IE 6 does not allow radio buttons to be checked if they don’t have a name attribute. KO will internally use uniqueName on those elements to ensure they can be checked.

Syntax

uniqueName: <binding-value>

Parameters

Parameter here will be Boolean value true or false or an expression resulting in Boolean like value. A unique name is generated by KO for the element for which this parameter is set to true or true-like value.

Example

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

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

   <body>
      <p>Enter your pet's name: 
         <input data-bind = "value: someValue, uniqueName: true" />
      </p>
   
      <p>
         <button data-bind = "click: showMessage">Click here to read message </button>
      </p>

      <script type = "text/javascript">
         function ViewModel() {
            this.someValue = ko.observable();
         
            this.showMessage = function() {
               alert(" Nice Name"+ "\nSee rendered markup to view unique name generated!!!");
            }
         };

         var vm = new ViewModel();
         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 uniquename-bind.htm file.

  • Open this HTML file in a browser.

  • Press F12 and observe the rendered markup. Unique name is generated by KO.


knockoutjs_declarative_bindings.htm

Advertisements
E-Books Store