Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make knockoutJS respond to property changes in real time?

The code bellow is supposed to do the following:

  1. When I input a new name, it will show me "Welcome: xxx" in the span.
  2. When I delete all the characters in the textbox, nothing will be shown in the span.

The issue is that when I remove one word (suppose the textbox's value is "Bill Gates" in default), and I removed "Gates", I want the span shows me "Bill" in real time not when I leave the field.

So how to make KnockoutJS support "Real Time" property changes? I want to see the span changing as I type instead of when leaving the textbox or press the "Enter" key.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Knock Out Sample</title>
</head>
<body>
      Your Name, please: <input type="text" data-bind="value: myName" />
      <br />
      <span data-bind="text: myNameShown, visible: showWelcome" id="spName"></span>
</body>

<script src="KnockOutJS.js" type="text/javascript"></script>

<script type="text/javascript">
     var model = {
         myName: ko.observable("Bill Gates")
     };

     model.myNameShown = ko.dependentObservable(function () {
         return "Welcome: " + model.myName();
     }, model);

     model.showWelcome = ko.dependentObservable(function () {
         return model.myName() && model.myName().trim() != "";
     }, model);

     ko.applyBindings(model);
</script>
</html>
like image 502
xqMogvKW Avatar asked Nov 18 '25 22:11

xqMogvKW


1 Answers

The answer by @Luis utilizing valueUpdate: 'afterkeydown' in combo with the value binding works great, but if you use Knockout 3.2 or higher there's a preferred alternative answer: use the textInput binding. This binding is more succinct, and handles cross-browser quirks. Use it like this:

ko.applyBindings({myName: ko.observable('initial value')});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

Input: <input type="text" data-bind="textInput: myName" />
<hr />
Result: <strong data-bind="text: myName"></strong>

To quote aforementioned docs about the difference between textInput and value:

Although the value binding can also perform two-way binding between text boxes and viewmodel properties, you should prefer textInput whenever you want immediate live updates. The main differences are:

  • Immediate updates [...]
  • Browser event quirks handling [...]
like image 92
Jeroen Avatar answered Nov 21 '25 11:11

Jeroen