Reputation: 34188
here two textboxs and one span is bind by knockout. the example i got is very easy to understand. here is the code.
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth"));
when the code run the whatever value are passing that is reflected but when i change one textbox value then changed data is not reflected immediately when keyup
occur but when focus change then changed data is reflected in span. so guide me if i want to change data on keyup then what i need to change in code. thanks
Upvotes: 3
Views: 1332
Reputation: 35793
You can pass in an additional value valueUpdate
in your databind.
- valueUpdate
If your binding also includes a parameter called valueUpdate, this defines additional browser events KO should use to detect changes besides the change event. The following string values are the most commonly useful choices:
- "keyup" - updates your view model when the user releases a key
- "keypress" - updates your view model when the user has typed a key. Unlike keyup, this updates repeatedly while the user holds a key down
- "afterkeydown" - updates your view model as soon as the user begins typing a character. This works by catching the browser’s keydown event and handling the event asynchronously.
Of these options, "afterkeydown" is the best choice if you want to keep your view model updated in real-time.
From http://knockoutjs.com/documentation/value-binding.html
So your bindings would be:
<p>First name: <input data-bind="value: firstName, valueUpdate: 'keyup'" /></p>
<p>Last name: <input data-bind="value: lastName, valueUpdate: 'keyup'" /></p>
Upvotes: 2
Reputation: 16465
You should use valueUpdate
binding for that:
<p>First name: <input data-bind="value: firstName, valueUpdate: 'keyup'" /></p>
<p>Last name: <input data-bind="value: lastName, valueUpdate: 'keyup'" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
Here is a link to documentation: http://knockoutjs.com/documentation/value-binding.html
Upvotes: 3