I have noticed that I cannot get some of the Knockout live tutorials working or basic examples that should demonstrate the observable data binding.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="utf-8" />
<title>Testing</title>
<script type="text/javascript" src="knockout.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function TestViewModel() {
this.Name = ko.observable("Testing");
}
$(function() {
ko.applyBindings(new TestViewModel());
});
</script>
</head>
<body>
<h1>Testing Knockout.js</h1>
<div>
<div>
<span data-bind="text: Name"></span>
</div>
<div>
<input type="text" data-bind="value: Name"></input>
</div>
</div>
</body>
</html>
So when I open this up in Google Chrome or Firefox I would expect the value of the span tag to change as I change the text in the input, however this is not the case. Can someone please explain why the above does not work? (This code was pretty much copied from the documentation on the website)
Thanks, Alex.
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted. The main advantage of KO is that it updates our UI automatically when the view model changes.
To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.
As of KO version 3.2 (as Salvador Dali answer's pointed out) you should use the textinput
binding for instant updates:
<input data-bind="textInput: userName" />
In you are using an earlier Knockout version and the value
binding, then you should make the following changes:
By default knockout updates the value of the observables on the change event (e.g when the focus of the textbox is lost).
If you want instant update you need to specify the valueUpdate
option where the possible events are: keyup
, keypress
, afterkeydown
see more info in the documentation.
So change your value
binding:
<input type="text" data-bind="value: Name, valueUpdate: 'afterkeydown'"></input>
Demo JSFiddle.
The accepted answer is correct, but in a new KO version 3.2 they added textinput binding. So instead of value
binding you can use textInput
:
<input data-bind="textInput: userName" />
It does two important things:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With