This really bothers me. Please have a look at the Hello World example of knockout.js.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Home Page</title>
<script src="knockout-1.2.1.debug.js" type="text/javascript"></script>
<script type="text/javascript">
// Here's my data model
var viewModel = {
firstName: ko.observable("Planet"),
lastName: ko.observable("Earth")
};
viewModel.fullName = ko.dependentObservable(function () {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return viewModel.firstName() + " " + viewModel.lastName();
});
ko.applyBindings(viewModel); // This makes Knockout get to work
</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>
It seems, that the binding doesn't work. If I alert(viewModel.fullName());
I get "Planet Earth" as expected. But neither the input elements nor the span gets filled with data.
What am I doing wrong?
Here is a zip file which includes both my file and knockout.js
This is a working version of the KnockoutJs tutorial.
The
ko.applyBindings()
should called once the view gets loaded then the data gets binded to the controls automatically.If the values are not binding just fire up a check functionality before you make use of the array. In knockout you can do this like
Just add window.onload= function() in the beginning of script..
Looking at the demos for knockout.js, you're missing one thing. You're not sending the view model as a parameter in to the dependentObservable function:
Your issue is that you are calling ko.applyBindings too soon.
You want to either move your script tag to the bottom or execute it in an onload or something like jQuery's ready function.