KnockoutJS Introduction

From WikiOD

Remarks[edit | edit source]

This section provides an overview of what knockout.js is, and why a developer might want to use it.

It should also mention any large subjects within knockout.js, and link out to the related topics. Since the Documentation for knockout.js is new, you may need to create initial versions of those related topics.

Versions[edit | edit source]

Version Notes Release Date
3.4.2 Bug fixes 2017-03-06
3.4.1 Bug fixes 2016-11-08
3.4.0 2015-11-17
3.3.0 2015-02-18
3.2.0 Introduced component binding 2014-08-12
3.1.0 2014-05-14
3.0.0 See also: upgrade (from 2.x) notes 2013-10-25
2.3.0 Last 2.x release 2013-07-08
2.0.0 2011-12-21
1.2.1 Last 1.x release 2011-05-22
1.0.0 2010-07-05

Getting Started: Hello world![edit | edit source]

Creating an HTML document and enabling knockout.js[edit | edit source]

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.


How the created file works[edit | edit source]

  1. A debug version of knockout is loaded from an external source (cdnjs)

Code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>
  • A viewmodel instance is created that has observable properties. This means knockout is able to detect changes and update the UI accordingly.

Code:

var appVM = new ViewModel();
  • Knockout checks the DOM for data-bind attributes and updates the UI using the provided viewmodel.

Code:

ko.applyBindings(appVM);
  • When it encounters a 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>

Installation or Setup[edit | edit source]

Knockout is available on most JavaScript platforms, or as a standalone script.

Include as a script[edit | edit source]

You can download the script from it's download page, then include it in your page with a standard script tag

<script type='text/javascript' src='knockout-3.4.0.js'></script>

Using a CDN[edit | edit source]

You can also include knockout from either the Microsoft CDN, or CDNJS

<script type='text/javascript' src='//ajax.aspnetcdn.com/ajax/knockout/knockout-3.4.0.js'></script>

OR

<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js'></script>

Install from npm[edit | edit source]

npm install knockout

optionally you can add the --save parameter to keep it in your package.json file

Install from bower[edit | edit source]

bower install knockout

optionally you can add the --save parameter to keep it in your bower.json file

Install from NuGet[edit | edit source]

Install*Package knockoutjs

Computed Observables[edit | edit source]

Computed observables are functions that can "watch" or "react" to other observables on the view model. The following example shows how you would display the total number of users and the average age.

Note: The example below can also make use of pureComputed() (introduced in v3.2.0) since the function simply calculates something based on other view model properties and returns a value.

<div>
  Total Users: <span data-bind="text: TotalUsers">2</span><br>
  Average Age: <span data-bind="text: UsersAverageAge">32</span>
</div>
var viewModel = function() {

    var self = this;

    this.Users = ko.observableArray([
        { Name: "John Doe", Age: 30 },        
        { Name: "Jane Doe", Age: 34 }
    ]);

    this.TotalUsers = ko.computed(function() {
        return self.Users().length;
    });

    this.UsersAverageAge = ko.computed(function() {
        var totalAge = 0;
        self.Users().forEach(function(user) {
            totalAge += user.Age;
        });

        return totalAge / self.TotalUsers();
    });
};

ko.applyBindings(viewModel);

Credit:Stack_Overflow_Documentation