This example of knockout js works so when you edit a field and press TAB, the viewmodel data and hence the text below the fields is updated.
How can I change this code so that the viewmodel data is updated every keypress?
<!doctype html>
<html>
<title>knockout js</title>
<head>
<script type="text/javascript" src="js/knockout-1.1.1.debug.js"></script>
<script type="text/javascript">
window.onload= function() {
var viewModel = {
firstName : ko.observable("Jim"),
lastName : ko.observable("Smith")
};
viewModel.fullName = ko.dependentObservable(function () {
return viewModel.firstName() + " " + viewModel.lastName();
});
ko.applyBindings(viewModel);
}
</script>
</head>
<body>
<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>
</body>
</html>
From the documentation
If you want it to do updates on
afterkeydown
"by default," you could inject thevalueUpdate
binding in thevalue
binding handler. Just supply a newallBindingsAccessor
for the handler to use that includesafterkeydown
.If you're not comfortable "overriding" the
value
binding, you could give the overriding custom binding a different name and use that binding handler.demo
A solution like this would be suitable for Knockout version 2.x. The Knockout team has fleshed out a more complete binding for text-like inputs through the textInput binding in Knockout version 3 and up. It was designed to handle all text input methods for text inputs and
textarea
. It will even handle real time updating which effectively renders this approach obsolete.In version 3.2 you can simply use textinput binding.:
It does two important things:
So no need for additional modules, custom controls and other things.
Jeff Mercado's answer is fantastic, but unfortunately broken with Knockout 3.
But I found the answer suggested by the ko devs while working through Knockout 3 changes. See the bottom comments at https://github.com/knockout/knockout/pull/932. Their code:
http://jsfiddle.net/mbest/GKJnt/
Edit Ko 3.2.0 now has a more complete solution with the new "textInput" binding. See SalvidorDali's answer