KnockoutJS - textInput Binding


Advertisements


This binding is used to create two-way binding between text box or textarea and ViewModel property. The difference between this and value binding is that this binding makes immediate updates available from HTML DOM for various input types.

Syntax

textInput: <binding-value>

Parameters

  • HTML DOM element's value property is set to parameter value. Earlier values will be overwritten.

  • If the parameter is something other than a Number or a String (such as an object or an array), the displayed text is equivalent to a String format.

  • If the parameter is an observable, then the elements value is updated as and when the underlying observable is changed. Element is processed only once, if no observable is used.

  • In most of the situations textInput is preferred over value binding due to the capacity of textInput to provide live updates from DOM for every input type and the ability to handle weird behavior of browsers.

Example

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

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

   <body>
      <p> Enter your reviews here: <br><br><textarea rows=5 
      data-bind = "textInput: someReview" ></textarea><br></p>
      
      <p> You entered : <span data-bind = "text: someReview"></span></p>

      <script type = "text/javascript">
         function ViewModel() {
            this.someReview = ko.observable('');
         };

         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 textinput-bind.htm file.

  • Open this HTML file in a browser.

  • The data entered in textarea is updated in ViewModel immediately.

Observations

textInput vs Value binding

textInput binding provides immediate live updates. The main differences between textInput and value Binding are −

Immediate updates − By default, the value binding only updates the model when the user moves the focus out of the textbox. The textInput binding updates the model instantly after each keystroke or on other text entry mechanism.

Browser event weirdness handling − Browsers are highly unpredictable in the events that fire in response to the unusual text entry mechanism such as dragging, cutting, or allowing auto-complete suggestion. The value binding does not handle all text entry cases on all browsers.

The textInput binding is especially designed to handle a wide range of weird behavior of browsers. This way it provides consistent and instant model updates, even in case of unusual text entry mechanisms.


knockoutjs_declarative_bindings.htm

Advertisements
E-Books Store