Knockoutjs tutorial-TutorialsPoint
Knockoutjs tutorial-TutorialsPoint
This tutorial covers most of the topics required for a basic understanding of KnockoutJS
and explains its various functionalities.
Audience
This tutorial is designed for software programmers who want to learn the basics of
KnockoutJS and its programming concepts in a simple and easy way. This tutorial will give
you enough understanding on the components of KnockoutJS with suitable examples.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of HTML, CSS,
JavaScript, Document Object Model (DOM), and any text editor. As we are going to develop
web-based application using KnockoutJS, it will be good if you have an understanding on
how the Internet and web-based applications work.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]
i
KnockoutJS
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Architecture ............................................................................................................................................ 6
Architecture ............................................................................................................................................ 8
sort() Method........................................................................................................................................ 23
ii
KnockoutJS
Observations ......................................................................................................................................... 49
Observations ......................................................................................................................................... 56
Observations ......................................................................................................................................... 62
If Binding ............................................................................................................................................... 63
Observations ......................................................................................................................................... 65
Observations ......................................................................................................................................... 70
iii
KnockoutJS
Observations ......................................................................................................................................... 75
Observations ......................................................................................................................................... 79
Observations ......................................................................................................................................... 87
iv
KnockoutJS
v
1. KNOCKOUTJS ─ OVERVIEW KnockoutJS
KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps
developers build rich and responsive websites. The model separates the application's Model
(stored data), View (UI) and View Model (JavaScript Representation of model).
Features of KnockoutJS
Here is a list 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.
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.
Most important of all KnockoutJS is open source and hence free for use.
6
KnockoutJS
KnockoutJS is fully documented. The official site has full documentation including API
docs, live examples, and interactive tutorials.
7
2. KNOCKOUTJS ─ ENVIRONMENT SETUP KnockoutJS
It is very easy to use KnockoutJS. Simply refer the JavaScript file using <script> tag in HTML
pages.
You can download production build of Knockout.js from its official website:
A page as in the following image will be displayed. Click the download link and you will
get the latest knockout.js file.
Update the src attribute to match the location where the downloaded files are kept.
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/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
library.
Example
8
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 -->
<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>
9
KnockoutJS
</body>
</html>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"> </script>
We have two input boxes: First String and Second String. These 2 variables are initialized
with values Enter First String and Enter Second String respectively in ViewModel.
This is how we are binding values from ViewModel to HTML elements using 'data-
bind' attribute in the body section.
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 earlier. Thus, any updates made to these strings automatically get
reflected in this derived string. There is no need of writing an extra code to accomplish this.
This is just a simple example. We will study about this concept in KnockoutJS - Computed
Observables chapter.
10
KnockoutJS
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.
Modify strings to "Hello" and "TutorialsPoint" and the output changes as follows.
11
3. KNOCKOUTJS ─ APPLICATION KnockoutJS
KnockoutJS is widely used for Single Page Applications - A website created with the ability to
retrieve all necessary data dynamically with a single page load reducing server round trips.
KnockoutJS is a client-side framework. This is a JavaScript library 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
View
View is nothing but user interface created using HTML elements and CSS styling.
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.
12
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 application 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.
13
4. KNOCKOUTJS ─ MVVM FRAMEWORK KnockoutJS
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.
14
KnockoutJS
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
15
KnockoutJS
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 implicit 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.
16
5. KNOCKOUTJS ─ OBSERVABLES KnockoutJS
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.
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 -->
<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 line is for the input box. As can be seen, we have used data-bind attribute to
bind yourName value to ViewModel.
The following line just prints the value of yourName. Note, that here data-bind type is the
text as we are simply reading the value.
In the following line, 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:
18
KnockoutJS
Data modification can take place either from the UI or from ViewModel. Irrespective of from
where the data is changed, the UI and ViewModel keeps synchronization among them. This
makes it a two-way-binding mechanism. In the above example, when you change your name
in the input box, ViewModel gets a new value. When you change yourName property from
inside ViewModel, then the UI receives a new value.
Sr.
Read/Write Operation & Syntax
No.
Read
1 To read value just call Observable property without parameters like:
AppViewModel.yourName();
Write
2
To write/update value in Observable property, just pass the desired value in parameter like:
AppViewModel.yourName('Bob');
Write multiple
3
Multiple ViewModel properties can be updated in a single row with the help of chaining-syntax like:
AppViewModel.yourName('Bob').yourAge(45);
Observable Arrays
Observable declaration takes care of data modifications of a single object. ObservableArray
works with the collection of objects. This is a very useful feature when you are dealing with
19
KnockoutJS
complex applications containing multiple type of values and changing their status frequently
based on the user actions.
Syntax
this.arrayName = ko.observableArray(); // It's an empty array
Observable array only tracks which objects in it are added or removed. It does not notify if
the individual object's properties are modified.
this.arrayName = ko.observableArray(['scott','jack']);
ObservableArray Functions
KnockoutJS has its own set of Observable array functions. They are convenient because:
Syntax is easy to use. For example, to insert an element into an array, you just need
to use arrayName.push('value') instead of arrayName().push('value').
Sr.
Methods & Description
No.
push('value')
1
Inserts a new item at the end of array.
pop()
2
Removes the last item from the array and returns it.
unshift('value')
3
Inserts a new value at the beginning of the array.
20
KnockoutJS
shift()
4
Removes the first item from the array and returns it.
reverse()
5
Reverses the order of the array.
sort()
6
Sorts array items in an ascending order.
splice(start-index,end-index)
7 Accepts 2 parameters - start-index and end-index - removes items starting from start to end index
and returns them as an array.
indexOf('value')
8
This function returns the index of the first occurrence of parameter provided.
slice(start-index,end-index)
9
This method slices out a piece of an array. Returns the items from start-index up to end-index.
removeAll()
10
Removes all items and returns them as an array.
remove('value')
11
Removes items that match the parameter and returns as an array.
remove(function(item) { condition })
12
Removes items which are satisfying the condition and returns them as an array.
remove([set of values])
13
Removes items that match with a given set of values.
destroyAll()
14
Marks all items in an array with property _destroy with value true.
destroy('value')
15 Searches for an item equal to the parameter and mark it with a special property _destroy with value
true.
destroy(function(item) { condition})
16
Finds all items which are satisfying the condition, marks them with property _destroy with true value.
destroy([set of values])
17
Finds the items that match with a given set of values, marks them as _destroy with true value.
21
KnockoutJS
Note: Destroy and DestroyAll Functions from ObservableArrays are mostly for 'Ruby on Rails'
developers only.
When you use destroy method, the corresponding items are not really deleted from array at
that moment but are made hidden by marking them with property _destroy with true value
so that they can't be read by UI. Items marked as _destroy equal to true are deleted later
while dealing with JSON object graph.
push() Method
Description
The KnockoutJS Observable push('value') method inserts a new item at the end of an array.
Syntax
arrayName.push('value')
Parameters
Accepts only one parameter, that is the value to be inserted.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Observable Array push() Method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate push() method.</p>
<p>Enter name: <input data-bind='value: empName' /></p>
<p><button data-bind="click: addEmp">Add Emp </button></p>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
22
KnockoutJS
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
//Initial Values
this.addEmp = function() {
if (this.empName() != "") {
this.empArray.push(this.empName()); //insert accepted value in array
this.empName("");
}
}.bind(this);
}/
var emp = new EmployeeModel();
ko.applyBindings(emp);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
pop() Method
Description
23
KnockoutJS
The KnockoutJS Observable pop() method removes the last item from an array and returns
it.
Syntax
arrayName.pop()
Parameters
Does not accept any parameters.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray pop method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate pop()method.</p>
<button data-bind="click: popEmp">Remove Emp</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.popEmp = function() {
this.empArray.pop();
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
24
KnockoutJS
</html>
Output
Let's carry out the following steps to see how the above code works:
Click the Remove Emp button and observe that the last element is removed.
unshift() Method
Description
The KnockoutJS Observable unshift('value') method inserts a new item at the beginning of
the array.
Syntax
arrayName.unshift('value')
Parameters
Accepts one parameter, that is the value to be inserted.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray unshift method</title>
25
KnockoutJS
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate unshift() method.</p>
<p>Enter name: <input data-bind='value: empName' /></p>
<button data-bind="click: unshiftEmp">Add Emp in Beginning</button><br><br>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.unshiftEmp = function() {
if (this.empName() != "") {
this.empArray.unshift(this.empName()); // insert at the beginning
this.empName("");
}
}.bind(this);
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
26
KnockoutJS
shift() Method
Description
The KnockoutJS Observable shift() method removes the first item from the array and returns
it.
Syntax
arrayName.shift()
Parameters
Does not accept any parameter.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray shift method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate shift() method.</p>
<button data-bind="click: shiftEmp">Remove First Emp</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
27
KnockoutJS
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.shiftEmp = function() {
this.empArray.shift(); //remove first item
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
reverse() Method
Description
The KnockoutJS Observable reverse() method reverses the order of the array.
28
KnockoutJS
Syntax
arrayName.reverse()
Parameters
Does not accept any parameter.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray reverse method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate reverse() method.</p>
<button data-bind="click: revEmp">Reverse Array</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.revEmp = function() {
this.empArray.reverse(); // reverse order
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
29
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
sort() Method
Description
The KnockoutJS Observable sort() method sorts all items in the array.
By default, items are sorted in an ascending order. For sorting an array in a descending order,
use reverse() method on sorted array.
Syntax
arrayName.sort()
Parameters
Does not accept any parameter.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray sort method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
30
KnockoutJS
</head>
<body>
<p>Example to demonstrate sort() method.</p>
<button data-bind="click: sortEmp">Sort Array</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.sortEmp = function() {
this.empArray.sort(); //sort array
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
31
KnockoutJS
splice() Method
Description
The KnockoutJS Observable splice() method takes 2 parameters specifying the start-index
and the end-index. It removes items starting from start to end index and returns them as an
array.
Syntax
arrayName.splice(start-index,end-index)
Parameters
Accepts 2 parameters, start-index is start index and end-index is end index.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray splice method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate splice() method.</p>
<button data-bind="click: spliceEmp">Splice Emp</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
32
KnockoutJS
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.spliceEmp = function() {
alert("Splice is removing items from index 1 to 3(If exists).");
this.empArray.splice(1,3); // remove 2nd,3rd and 4th item, as array
index starts with 0.
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
33
KnockoutJS
indexOf() Method
Description
The KnockoutJS Observable indexOf('value') method returns the index of the first
occurrence of the parameter provided. This function will return -1, if no matching element is
found.
Syntax
arrayName.indexOf('value')
Parameters
Accepts 1 parameter, whose index will be returned.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray indexOf method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate indexOf() method.</p>
<p>Index of Employee 'Jordan':<span data-bind="text:
empArray().indexOf('Jordan')"></span ></p>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
34
KnockoutJS
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
35
KnockoutJS
36