English 中文(简体)
KnockoutJS - Quick Guide
  • 时间:2024-11-03

KnockoutJS - Quick Guide


Previous Page Next Page  

KnockoutJS - Overview

KnockoutJS is basically a pbrary written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites. The model separates the apppcation s Model (stored data), View (UI) and View Model (JavaScript Representation of model).

KnockoutJS was developed and is maintained as an open source project by Steve Sanderson, a Microsoft employee on July 5, 2010. KO is an abbreviation used for KnockoutJS. KO supports all mainstream browsers - IE 6+, Firefox 3.5+, Chrome, Opera, Safari (desktop/mobile).

Features of KnockoutJS

Here is a pst of some of the most prominent features of KnockoutJS −

    Declarative Binding − HTML DOM elements are connected to the model through data-bind attribute using a very simple syntax. It is made easy to achieve responsiveness using this feature.

    Automatic UI Refresh − Any changes made to view the model data are reflected in the UI automatically and vice-versa. No need of writing extra code.

    Dependency Tracking − Relationship between KO attributes and KO pbrary functions/components is transparent. Automatically tracks data changes in KO attribute and updates respective affected areas.

    Templating − Templates are a simple and convenient way to build complex UI structures - with the possibipty of repeating or nesting blocks - as a function of view model data.

    Extensible − Extends custom behavior very easily.

Why Use KnockoutJS?

    KnockoutJS pbrary provides an easy and clean way to handle complex data-driven interfaces. One can create self-updating UIs for Javascript objects.

    It is pure JavaScript Library and works with any web framework. It s not a replacement of JQuery but can work as a supplement providing smart features.

    KnockoutJS pbrary file is very small and pghtweight.

    KnockoutJS is independent of any other framework. It is compatible with other cpent or server side technologies.

    Most important of all KnockoutJS is open source and hence free for use.

    KnockoutJS is fully documented. The official site has full documentation including API docs, pve examples, and interactive tutorials.

KnockoutJS - Environment Setup

It is very easy to use KnockoutJS. Simply refer the JavaScript file using <script> tag in HTML pages.

Knockout.js can be accessed in the following ways −

    You can download production build of Knockout.js from its official website

    A page as in the following image will be displayed. Cpck on download pnk and you will get the latest knockout.js file.

Knockoutjs Setup

Now refer the file as shown in the following code.

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

Update the src attribute to match the location where the downloaded files are kept.

    You can refer to the KnockoutJS pbrary from CDNs −

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

    Alternatively you can refer to a minified version of KnockoutJS pbrary from CDNJS as follows −

<script src = "https://cdnjs.cloudflare.com/ajax/pbs/knockout/3.3.0/knockout-min.js" 
   type = "text/javascript"></script>

Note − In all the chapters for this tutorial, we have referred to CDN version of the KnockoutJS pbrary.

Example

KnockoutJS is based on Model-View-ViewModel (MVVM) pattern. We will study this pattern in depth in chapter KnockoutJS - MVVM Framework. First let s take a look at a simple example of KnockoutJS.

<!DOCTYPE html>
   <head>
      <title>KnockoutJS Simple Example</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" 
         type = "text/javascript"></script>
   </head>

   <body>
      <!-- This is called "view" of HTML markup that defines the appearance of UI -->

      <p>First String: <input data-bind = "value: firstString" /></p>
      <p>Second String: <input data-bind = "value: secondString" /></p>

      <p>First String: <strong data-bind = "text: firstString">Hi</strong></p>
      <p>Second String: <strong data-bind = "text: secondString">There</strong></p>

      <p>Derived String: <strong data-bind = "text: thirdString"></strong></p>

      <script>
         <!-- This is called "viewmodel". This javascript section defines the data and 
            behavior of UI -->

         function AppViewModel() {
            this.firstString = ko.observable("Enter First String");
            this.secondString = ko.observable("Enter Second String");

            this.thirdString = ko.computed(function() {
               return this.firstString() + " " + this.secondString();
            }, this);
         }

         // Activates knockout.js
         ko.applyBindings(new AppViewModel());
      </script>

   </body>
</html>

The following pne refers to KnockoutJS pbrary.

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

This pne refers KnockoutJS pbrary.

We have two input boxes: First String and Second String. These 2 variables are initiapzed with values Enter First String and Enter Second String respectively in ViewModel.

<p>First String: < input data-bind = "value: firstString" /> &lt/p>

This is how we are binding values from ViewModel to HTML elements using data-bind attribute in the body section.

Here, firstString refers to ViewModel variable.

this.firstString = ko.observable("Enter First String");

ko.observable is a concept which keeps an eye on the value changes so that it can update the underlying ViewModel data.

To understand this better, let s update the first input box to "Hello" and the second input box to "TutorialsPoint". You will see the values are updated simultaneously. We will study more about this concept in KnockoutJS - Observables chapter.

this.thirdString = ko.computed(function() {
   return this.firstString() + " " + this.secondString();
}, this);

Next, we have computed function in viewmodel. This function derives the third string based on 2 strings mentioned earper. Thus, any updates made to these strings automatically get reflected in this derived string. There is no need of writing an extra code to accomppsh this. This is just a simple example. We will study about this concept in KnockoutJS - Computed Observables chapter.

Output

Save the above code as my_first_knockoutjs_program.html. Open this file in your browser and you will see an output as the following.

first example

Modify strings to "Hello" and "TutorialsPoint" and the output changes as follows.

Hello TutorialsPoint Example

KnockoutJS - Apppcation

KnockoutJS is widely used for Single Page Apppcations - A website created with the abipty to retrieve all necessary data dynamically with a single page load reducing server round trips.

KnockoutJS is a cpent-side framework. This is a JavaScript pbrary which makes it very easy to bind HTML to domain data. It implements a pattern called Model-View-ViewModel (MVVM). Observables is the magic ingredient of KnockoutJS. All data remains in sync because of Observable attribute.

Architecture

KnockoutJS Architecture

View

View is nothing but user interface created using HTML elements and CSS stypng.

You can bind HTML DOM elements to data model using KnockoutJS. It provides 2-way data binding between View and ViewModel using data-bind concept, which means any updates done in the UI are reflected in the data model and any changes done in the data model are reflected in the UI. One can create self-updating UI with the help of knockoutJS.

ViewModel

ViewModel is a JavaScript object, which contains necessary properties and functions to represent data. View and ViewModel are connected together with declarative data-bind concept used in HTML. This makes it easy to change HTML without changing ViewModel. KnockoutJS takes care of automatic data refresh between them through the use of Observables.

Synchronization of data is achieved through binding DOM elements to Data Model, first using data-bind and then refreshing these 2 components through the use of Observables. Dependency tracking is done automatically due to this synchronization of data. No extra coding is required to achieve it. KnockoutJS allows to create direct connection between the display and underlying data.

You can create your own bindings called as custom bindings for apppcation specific behaviors. This way Knockout gives direct control of how you want to transform your data into HTML.

Model

Model is the domain data on the server and it gets manipulated as and when the request is sent/received from ViewModel.

The data could be stored in database, cookie, or other form of persistent storage. KnockoutJS does not worry about how it is stored. It is up to the programmer to communicate between the stored data and KnockoutJS.

Most of the times, data is saved and loaded via an Ajax call.

KnockoutJS - MVVM Framework

Model-View-ViewModel (MVVM) is an architectural design pattern for developing software apppcations. MVVM was developed by Microsoft Architect John Gossman in 2005. This pattern is derived from Model-View-Controller (MVC) pattern. The advantage of MVVM is that it separates the apppcation layer s graphical user interface from business logic. MVVM is responsible for handpng data from the underlying model in such a way that it is represented and managed very easily. ViewModel in MVVM represents an abstract version of View s state and actions.

The view classes do not know that Model and ViewModel classes exists, also Model and ViewModel does not know that View exists. Model is also unaware that ViewModel and View exists.

Architecture

MVVM Architecture

View

View is a Graphical User Interface created using markup language to represent data. View binds to properties of a ViewModel through data-bind concept, which indirectly connects to the model data. View need not be changed for any alteration done in ViewModel. Changes made to data in ViewModel is automatically propagated in View due to binding.

Model

Model is domain data or business object, which holds real-time data. Model does not carry behaviors. Behavior is mostly implemented in business logic.

ViewModel

ViewModel is the center place, where data from Model and View s display logic are bundled together. ViewModel holds the dynamic state of data. There is an imppcit binder in between View and ViewModel to communicate with each other. This binding is inclusive of declarative data and command binding. Synchronization of View and ViewModel is achieved through this binding. Any change made in View is reflected in ViewModel, and similarly any change in ViewModel gets automatically reflected in View. Existence of this 2-way binding mechanism is a key aspect of this MVVM pattern.

KnockoutJS - Observables

KnockoutJS is build upon the following 3 important concepts.

    Observables and dependency tracking between them - DOM elements are connected to ViewModel via data-bind . They exchange information through Observables. This automatically takes care of dependency tracking.

    Declarative Bindings between UI and ViewModel - DOM elements are connected to ViewModel via data-bind concept.

    Templating to create re-usable components - Templating provides a robust way to create complex web apppcations.

We will study Observables in this chapter.

As the name specifies, when you declare a ViewModel data/property as Observable, any data modification each time automatically gets reflected at all places the data is used. This also includes refreshing the related dependencies. KO takes care of these things and there is no need to write extra code to achieve this.

Using Observable, it becomes very easy to make UI and ViewModel communicate dynamically.

Syntax

You just need to declare ViewModel property with function ko.observable() to make it Observable.

this.property = ko.observable( value );

Example

Let s take a look at the following example which demonstrates the use of Observable.

<!DOCTYPE html>
   <head>
      <title>KnockoutJS Observable Example</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" 
         type = "text/javascript"></script>
   </head>
   
   <body>
      <!-- This is called "view" of HTML markup that defines the appearance of UI -->

      <p>Enter your name: <input data-bind = "value: yourName" /></p>
      <p>Hi <strong data-bind = "text: yourName"></strong> Good Morning!!!</p>

      <script>
         <!-- This is called "viewmodel". This javascript section defines the data and behavior of UI -->

         function AppViewModel() {
            this.yourName = ko.observable("");
         }

         // Activates knockout.js
         ko.applyBindings(new AppViewModel());
      </script>
   </body>
</html>

The following pne is for the input box. As can be seen, we have used data-bind attribute to bind yourName value to ViewModel.

<p>Enter your name: <input data-bind = "value: yourName" /> <p>

The following pne just prints the value of yourName. Note, that here data-bind type is the text as we are simply reading the value.

<p>Hi <strong data-bind = "text: yourName"></strong> Good Morning!!!</p>

In the following pne, ko.observable keeps an eye on yourName variable for any modification in data. Once there is a modification, the corresponding places also get updated with the modified value. When you run the following code, an input box will appear. As and when you update that input box, the new value will get reflected or refreshed in places wherever it is used.

this.yourName = ko.observable("");

Output

Let s carry out the following steps to see how the above code works −

    Save the above code in first_observable_pgm.htm file.

    Open this HTML file in a browser.

    Enter the name as Scott and observe that the name is reflected in the output.