Create an HTML file and include knockout.js
via a <script>
tag.
<!DOCTYPE html>
<html>
<head>
<title>Hello world! (knockout.js)</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>
</body>
</html>
Add a second <script>
tag under the knockout script. In this script tag, we'll initialize a view model and apply data binds to our Document.
<script>
var ViewModel = function() {
this.greeting = ko.observable("Hello");
this.name = ko.observable("World");
this.appHeading = ko.pureComputed(function() {
return this.greeting() + ", " + this.name() + "!";
}, this);
};
var appVM = new ViewModel();
ko.applyBindings(appVM);
</script>
Now, continue creating a view by adding some HTML to the body:
<section>
<h1 data-bind="text: appHeading"></h1>
<p>Greeting: <input data-bind="textInput: greeting" /></p>
<p>Name: <input data-bind="textInput: name" /></p>
</section>
When the HTML document is opened and the scripts are executed, you'll see a page that says Hello, World!. When you change the words in the <input>
elements, the <h1>
text is automatically updated.
Code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>
Code:
var appVM = new ViewModel();
data-bind
attributes and updates the UI using the provided viewmodel.Code:
ko.applyBindings(appVM);
text
binding, knockout uses the property's value as it is defined in the bound viewmodel to inject a text node:Code:
<h1 data-bind="text: appHeading"></h1>