In this tutorial, I am going to create a simple Hello World example using Knockout js. Knockout Js based on MVVM framework.

Hello World Example using knockout js:

To get started with Knockout Js we need to include reference to following knockout js library to our application.

  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script>

Following are the steps for creating Simple World example using Knockout js.

  1. Create ViewModel
  2. Data Binding:
  3. Initialize Knockout
  4. Update UI dynamically.

Create ViewModel:

Following is a way to represent ViewModel.

      function ViewModel() {

          this.name = ko.observable("Debug On Web");

      }

Another way to represent ViewModel is:

var ViewModel = {

    name: ko.observable("Debug On Web ")

}

Data Binding:

Following piece of code that specifies how to bind HTML DOM element with data.

<div  class="input-group input-group-lg">

    <input class="form-control col-md-8" data-bind='value: name, valueUpdate: "afterkeydown"'/>

  </div>

  <h1>Hello, <span data-bind="text: name"></span></h1>

Initialize Knockout:

Following is a code to initialize knockout framework.

   ko.applyBindings(new ViewModel());

Update UI dynamically.

The code that does the magic is “observable()” method call. To achieve dynamic update behavior, one needs to declare your model properties as “observables”.

The method that achieves the dynamic update behavior is observable(). We need to declare our model properties as observables.

Here is the complete example:

<!DOCTYPE html>

<html>
<head>
<title>Hello Knockout</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</head>
<body class="container">
<div class="page-header">
<h1>Knockout Js Hello World Example</h1>
</div>
<div class="input-group input-group-lg">
<input class="form-control col-md-8" data-bind='value: name, valueUpdate: "afterkeydown"'/>
</div>
<h1>Hello, <span data-bind="text: name"></span></h1>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script>
<script>
function ViewModel() {
this.name = ko.observable("Debug On Web");
}
ko.applyBindings(new ViewModel());
</script>
</body>
</html>

Output:

Hello World example using Knockout js

You can find the demo here.

View More:

Conclusion:

I hope you understand how to create your first application using Knockout js. Your valuable comments and suggestions are always welcome to me.

Thank You.

Leave a Comment