Working with Knockout.js Part 6: Working with text binding

Working with Knockout.js Part 5: Working with visible binding

Working with Knockout.js Part 4: Observable Arrays

Working with Knockout.js Part 3: Working with Observables

Working with Knockout.js part 2: Understanding MVVM

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

In last post we started learning about bindings. We had a look on visible binding . In this post we will learn a very important text binding.

Text binding is used to set text property of view elements from the properties or values of ViewModel. You can bind text of a span as easily as depicted in following code snippet,


<script type="text/javascript">

<em id="__mceDel">
 var studentViewModel = {
 studentName: ko.observable('DJ'),

 }

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

Above we are creating a ViewModel named studentViewModel with property studentName. In HTML we are binding text property of span. So we can bind text property using following syntax,

Capture

Some time you may come across requirement to dynamically set the value of text binding. That is very much possible using functions and expressions to determine value of the text. Let us assume we have a function in ViewModel as give below,


var studentViewModel = {
 marks: ko.observable(90),
 }

And we can create computed function as following. This function will determine grade of the student.

 studentViewModel.grade = ko.computed(function () {

 if (this.marks > 96)
 return "Grade A";
 else
 return "Grade B";

 }, studentViewModel);

And we can simply bind computed property as text binding to span element on view. You can do this as following,


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

The other way we can dynamically set text binding value by using conditional statement while binding. We can do bind grade without computed function as following


<span data-bind="text:marks()> 10 ? 'Grade A':'Grade B'"></span>

In this way we can work with text binding in knockoutjs. In further posts we will discuss other bindings. I hope you find this post useful. Thanks for reading.

What is Method Invocation Pattern in JavaScript

In this post we will take a look on “Method Invocation Pattern” in JavaScript. In JavaScript when function is defined as property of object then it is known as Method

image

Assume we have a JavaScript object as following. In studentObject object property findgrade is a function. So we can say findgrade is a method.


var studentObject =
{
name: "dj",
marks: 89,
findgrade: function (marks) {
if (marks > 75) {
return "Grade A ";
}
else {
return "Grade B ";
}
}
}

Invocation of method is known as “Method Invocation Pattern”. We can invoke method using dot operator on object. Method can be invoked as following,


var grade = studentObject.findgrade(99);
alert(grade);

A Method can access its parent object using operator this. Let us go ahead and modify studentobject as following. Now you can see that we are accessing other properties of object in method using this operator.


var studentObject =
{
name: "dj",
marks: 89,
grade : null,
findgrade: function (marks) {
if (marks > 75) {
this.grade = "A";
}
else {
this.grade = "B";
}
}
}

Now we can set grade property with invocation of findgrade method.


studentObject.findgrade(99);
var grd = studentObject.grade;
alert(grd);

Binding of method to object happens when we execute the method. In this way we can work with Methods and Method Invocation Pattern in JavaScript. I hope you find this post useful. Thanks for reading.

How to find index of an item in JavaScript Object Array?

Recently while working I came across a scenario. I had to find index of a particular item on given condition from a JavaScript object array. In this post we will see how to find index of object from JavaScript array of object.

Let us assume we have a JavaScript array as following,


var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];

Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.

We can do that by iterating through the array and comparing value at the given key.


function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {

for (var i = 0; i < arraytosearch.length; i++) {

if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}

You can use the function to find index of a particular element as below,


var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);

In this way you can find index of an element in JavaScript array of object. I hope you find this quick post useful. Thanks for reading.

Working with Knockout.js Part 5: Working with visible Binding

Working with Knockout.js Part 4: Observable Arrays

Working with Knockout.js Part 3: Working with Observables

Working with Knockout.js part 2: Understanding MVVM

Getting started with Knockout.js

So far we have learnt about different aspects of ViewModel creation in Knockout.js. We learnt and discussed about MVVM, Observable, and Observable Array etc. In this post we will dig into various bindings’ capability of Knockout.js.

In simpler terms we can define Knockoutjs binding as a mechanism to establish relationship between view and ViewModel. View takes user action and pass the instruction to ViewModel. One of the most popular example of this could be clicking on a button or selection of an item on the View by user. After each action of user, view got the task to instruct ViewModel about the same. This is done through the BINDING. On the other hand we can define binding as manipulating DOM elements and their appearance on the basis of ViewModel properties. This can be also done through the BINDING again. Binding establish the relationship between View and ViewModel.

image

Knockoutjs binding can be categorised in different categories. We can say that there could binding could be to manage flow of data and DOM elements. There could be binding to manage display and style of DOM elements. There could be binding for user actions like click and touch. There could be binding to handle flow of data from Model to View.

In this post we will focus on working with visible binding. As name suggests visible binding decides whether a DOM element will be visible or not on the basis of ViewModel property value.

Assume you have div .You can apply visible binding to div as following

image

And a simple ViewModel can be as follows,

image

Some points about visible binding is worth discussing here, If value of ViewModel property will resolved to following values then bind DOM element view property will be set to block.

  • Null
  • undefined
  • number zero
  • Boolean false

For DOM elements if ViewModel property value is yielding to false then visible binding will always have more priority than CSS attributes.

image

Now to understand view binding in better way let us create two buttons. On click of one button div will be visible and on click of another button div visibility would be false. If you notice in ViewModel creation we have created property of ViewModel as observable property. Hence whenever value of this property will change, it will notify the View.

Let us assume we have HTML with one div and two buttons as following,

<body>
 <div data-bind="visible:displayViewDiv">
 <h2>This div will be visible and hidden thrugh visible binding </h2>
 </div>

<div>
 <button id="btnshowdiv" >Click to show Div</button>
 <button id="btnhidediv" >Click to hide Div</button>
 </div>
 <script>
 ko.applyBindings(divdispalyViewModel);
 </script>
</body>

We will create ViewModel with observable property .This property is bind with visible property of DOM element div. So ViewModel is created as follows,


var divdispalyViewModel = {

displayViewDiv: ko.observable(true)
 };

Now on click event of buttons we will set value of ViewModel property. Since property is an observable property hence it will notify view on value changed and view will get refresh automatically.


$(document).ready(function () {

 $('#btnshowdiv').click(function () {

divdispalyViewModel.displayViewDiv(true);
 });
 $('#btnhidediv').click(function () {

divdispalyViewModel.displayViewDiv(false);
 });

});

You will notice that Div is visible and hidden on clicking of buttons. We are handing div visibility using visible binding of Knockoutjs.

In this post we started with the discussion of binding. In further posts we will learn about other bindings as well. I hope you find this post useful. Thanks for reading.

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.

What is JSON?

For some of you this question might be the easiest to answer. But for many developers concept of JSON is not well understood. In my seminars when I use JSON data for demo, I find many developers do not have understanding of JSON. In this post I am trying to address this problem.

In simple words, “JSON is a data interchange format. Due to its lightweight characteristics it is being highly used to exchange data between different platforms and applications”

image

A simple JSON data representing Students can be like following,

image

You can see that JSON object follows key-value pair mechanism

  • Key should be always a string
  • Value may be a string , number , Boolean or an object

image

You can represent collection in JSON as well. That can be represented as array of JSON objects.

image

Information about many Students can be displayed in JSON format as following,

image

You can have JSON object as value of another JSON object as well.

image

Now let us see that how can we work with JSON in JavaScript. Let us say we have a HTML page as given in the following snippet,


<body>

<h2>Reading Student information from JSON data</h2>
 Name : <span id="namespan"></span> <br />
 Marks : <span id ="marksspan"></span><br />
 Addreess : <span id="addresssapn"></span> <br />

</body>

In JavaScript we have JSON data and we need to bind values of JSON in to the HTML elements. We can do that very simply as given in following snippet,


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

var Student = {
 "name": "dj",
 "marks": 89,
 "address":
 {
 "city": "Pune",
 "country": "India"
 }
 };
 document.getElementById('namespan').innerHTML = Student.name;
 document.getElementById('marksspan').innerHTML = Student.marks;
 document.getElementById("addresssapn").innerHTML = Student.address.city;

});

 </script>
</head>

When you browse HTML you will find HTML elements values are displaying JSON data.

image

I hope now you have some understanding of JSON. Thanks for reading this post.