Working with Knockout.js Part 4: Observable Arrays

Read Part 3: Working with Observables

Read Part 2: Understanding MVVM

Read Part 1: Getting Started

So far we have learnt fundamental of KO. In Part 3 we worked with single observable object. In this post we will take a look on working with Arrays of Observable. Focus of this post is to understand how Observable Array works

A simple observable array can be created as following,

image

Basic properties of observableArray is as follows,

  • It notifies view when item is added
  • It notifies view when item is removed

It is worth discussing here is that, ObservableArray is not responsible to determine whether state of the objects added in the array are observable or not? It only notifies when an object is added or removed from the array.

image

Let us assume that we have an observable object named studentViewModelObject as following,

var studentViewModelObject = {

studentName: "DJ",
 studentGrade: "B",
 studentMarks: 90

};

Next let us create a KO observable array and push (insert) this object in the array. We can create a observablearray and insert an object in that calling the push function. In the following code snippet we are finding the

  • Length of the array by calling arrayname().length
  • An object’s item can be printed as arrayname()[index].objectproperties

var studentArray = ko.observableArray();
 studentArray.push(studentViewModelObject);
 var studentarraylegnth = studentArray().length;
 var nameoffirststudent = studentArray()[0].studentName;

You notice that syntax of push in KO ObvservableArray is different than native JavaScript array push function.

image

There are many specific Knockout observableArray functions. We will discuss them one by one below, however technically you can apply all native JavaScript functions to KO observable array.

KO Observable functions are as follows,

IndexOf()

Returns index of item from the array. If item is not found then -1 is retuned. As an output we will get 0. Since studentViewModelObject is first element of the KO studentArray and KO ObservableArray is zero indexed.


var indexofstudentdj = studentArray.indexOf(studentViewModelObject);
 alert(indexofstudentdj);

slice()

This function will return items from the KO Observable array Slice takes two parameters. First parameter is starting index and second parameter is end index.


var lasttwoelementarray = studentArray.slice(1, 2);
 alert(lasttwoelementarray[0].studentName);

push()

This function is to insert an item at the last of the array. Push also notifies to view and subscribers on execution. This is same as native JavaScript push function with added notification capability. You can insert an item as following


studentArray.push(studentViewModelObject);

pop()

This function is to remove an item at the last of the array. Pop also notifies to view and subscribers on execution. This is same as native JavaScript pop function with added notification capability. You can pop an item as following


var item = studentArray.pop();

unshift()

This function will insert an item at the beginning of the array. This will add item at the 0th position of the array. This function will create notification also. Following code will insert studentViewModelObject3 at the beginning of the array. In alert you will get Ravish.


var studentViewModelObject3 = {

studentName: "Ravish",
 studentGrade: "A",
 studentMarks: 89

};
 studentArray.unshift(studentViewModelObject3);
 alert(studentArray()[0].studentName);

shift()

This function will delete an item at the beginning of the array. This will remove item at the 0th position of the array. This function will create notification also.


studentArray.shift();

reverse()

This function will reverse the array.


studentArray.reverse();

sort()

This function will sort array in alphabetical order or in ascending order.

studentArray.sort();

remove()

There are four ways you can remove item or items from KO Observable array. remove is specific to KO ObservableArray .

image

KO ObservableArray is very important and useful while creating web application using KnockOut.js. I hope you find this post useful. In further posts of this series we will learn other aspects of Knockout.js. Thanks for reading.

Working with Knockout.js Part 3: Working with Observables

Read here working with Knockout.js Part 2: Understanding MVVM

Read here Getting started with Knockout.js

So far we have learnt basics of Knockout.js. In last two posts we tried to understand need of KO and MVVM pattern.

One of the most essential and important feature of MVVM is, “When View Model changes View must be notified such that UI will be refreshed automatically

image

In Part 2 we created ViewModel as following. This is a simple ViewModel and would not notify View on changes of the property’s value.


var studentViewModel = {

studentName: "DJ",
studentGrade: "B",
studentMarks: 90

}

To enable automatic notification from ViewModel to View, we need to make properties of ViewModel as an OBSERVABLE PROPERTIES

We can make a property Observable as following

image

So we can rewrite StuentViewModel with automatic notification as following


var studentViewModel = {

studentName: ko.observable('DJ'),
studentGrade: ko.observable('B'),
studentMarks: ko.observable(90)

}

Now whenever value of property changes in the ViewModel View will be notified and UI will be refreshed automatically.

There is no need to change anything at View side. Different View Elements are now subscribed to ViewModel properties. Now whenever value at ViewModel will be changed , View will be notified.


<body>
<span data-bind="text:studentName"></span>
<span data-bind="text:studentGrade"></span>
<span data-bind="text:studentMarks"></span>
<script>
ko.applyBindings(studentViewModel);
</script>
</body>

We can read and write from observable using JavaScript getter and setter. A observable value can be read as following

image

We can write to observable as following

image

So now you see how much easier it is in KO to autmetically refresh UI on the chnages in ViewModel. Only we need to make ViewModel property as observable. I hop you find this post useful. In next post we will learn about Compound Observables. Thanks for reading.

Working with Knockout.js part 2: Understanding MVVM

Read here Getting started with Knockout.js part1

In last post we had a discussion on Getting started with Knockout. In this post we will go one step further and understand different aspects of MVVM pattern and how Knockout.js helps us in creating web application adhering to MVVM pattern.

Let us start our discussion with understanding MVVM. MVVM stands for Model-View-ViewModel.

image

As you see that each component of MVVM has dedicated task to do. View never talks to Model directly. You can say that data is model, business logic is ViewModel and user interface is View. Let us summarize discussion of Model, ViewModel and View in bullet points

Model

  • Persisted data
  • Data being fetched from server
  • Data can be in HTML local storage
  • Data can be fetched from server using AJAX call or any other mechanism of calling service from JavaScript

ViewModel

  • It contains business logic
  • Temporary data to be displayed on the View
  • It handles all the user actions to send commands to ViewModel
  • It is a JavaScript object

View

  • This is User Interface of the application
  • This displays data from the ViewModel.
  • This sends command to ViewModel
  • User interaction occurs here
  • This is HTML with CSS

Now let us take our discussion into working with Knockout. We can create a ViewModel just like creating a JavaScript object. Below we are creating ViewModel for Student.


var studentViewModel = {

studentName: "DJ",
 studentGrade: "B",
 studentMarks : 90

}

After creating ViewModel to work with all browsers and earlier versions of HTML, we need to activate Knockout. That can be done as following in a script

image

You can put this script

  1. Either in bottom of HTML document
  2. In document ready of jquery

In VS2012 intellisense is supported for Knockout.js. You can see that applyBindings takes two parameters.

image

Two parameters of applyBindings are

  1. First parameter is ViewModel
  2. Second parameter is part of the document on which ViewModel will be bind

Second parameter is very essential. Suppose a scenario in which you have multiple ViewModel and you want to associate them with different elements of HTML document. In that case you will have to create different Knockout bindings associating different ViewModel with different elements from View. Below we are applying studentViewModel to studentdiv from the View.

image

We can create View with Declarative Binding as following. Using data-bind attribute we can bind data from ViewModel to elements of View. You can see that in this case we are putting script to apply Knockout binding at the bottom of HTML document.


<body>
 <span data-bind="text:studentName"></span>
 <span data-bind="text:studentGrade"></span>
 <span data-bind="text:studentMarks"></span>
 <script>
 ko.applyBindings(studentViewModel);
 </script>
</body>

We saw in this post that how Knockout helps so easily to create an application adhering to MVVM pattern. We also learnt about different component of MVVM pattern. We learnt about creating ViewModel and View. We also learnt bindings in Knockout.js. In further posts we will discuss more complex aspects of Knockout.js. I hope you find this post useful. Thanks for reading.

Working with Knockout.js Part 1: Getting started with Knockoutjs

In this post we will take a look on Knockout.js. We will start with basic theoretical introduction and then to some basic demo on Knockout.js

image

Knockout.js helps us to create dynamic JavaScript UI using the MVVM pattern. It simplifies the task of linking Data Model to the dynamic JavaScript UI.

Knockout.js is a JavaScript library and it helps us to create high responsive, very rich and interactive JavaScript UI adhering to MVVM pattern. It simplifies the task of binding data from Data Model to JavaScript UI. It is a pure JavaScript library and it works with almost all the browsers. It is an open source project under the license of MIT. It is very compact in size. Its zipped size is 13kb and it can be added over any existing web application.

Essentially Knockout.js helps to link a Data Model to UI. It tracks the changes and dynamically updates the UI. It helps to perform two ways binding in between UI and Data Model. It updates certain section of UI dynamically when data in data model is changed. It simplifies the task of binding and dynamic updating the UI.

Some of the features of Knockout.js can be outlined as below,

  • It detects the data changes in data model and updates respective part of the UI.
  • It binds data and UI declaratively. In other words declarative binding between data model and UI can be done using Knockout.js
  • It helps to create custom behavior. Custom behavior can be created as declarative binding.
  • Custom behavior created by Knockout.js can be reused with very less lines of code.
  • It helps to create complex dynamic UI using declarative bindings.
  • It helps to edit JSON data on the JavaScript UI.

Knockout.js is JavaScript MVVM framework and it helps in

image

Further in the post, we will explore each features of Knockout.js. You can download Knockout.js from here. You will get many versions of Knockout.js to download on the download page. For usual production purpose you can choose to download knockout-versionnumber.js file.

After downloading add reference of Knockout.js. Reference can be added as following,

image

Next let us create a ViewModel. We are going to create ViewModel for Product. A ViewModel can be created as following. You can see that in knockout ViewModel is nothing but a JavaScript array,

image

Once you have created ViewModel you need to apply binding. Binding can be applied as below,

image

Last step is to bind values from ViewModel on the view. That can be done as following. Using data-bind attribute values from ViewModel can be bind to element on View.

image

A complete example of Product ViewModel data being bind with elements of View is given below,


<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="Scripts/jquery-1.7.1.js"></script>
 <script src="Scripts/knockout-2.2.0.js"></script>
 <script type="text/javascript" >
 $(document).ready(function () {

var ProductViewModel = {
 productname: "pen",
 productprice: 200,
 producttype :"education"
 };
 ko.applyBindings(ProductViewModel);

});

 </script>
</head>
<body>

<h2>Knockout Demo</h2>
 Product Name : <span id="namespan" data-bind="text:productname"></span> <br />
 Product Price : <span id ="pricespan" data-bind="text:productprice"></span><br />
 Product Type : <span id="typesapn" data-bind="text:producttype"></span> <br />

</body>
</html>

And as expected you will get values from ViewModel on View elements as following

image

This was small introduction of Knockout.js. In further posts we will get into more details of Knockout.js and see examples of its usage in real examples. I hope you find this post useful. Thanks for reading