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.

Thanks Julia Lerman for wonderful gift

This is one of the most excited day of my life. I got a gift from one of my ever inspiration Julia Lerman. She sent book authored by her with her autograph on that. I am simply happy. I thank Julie and Rowan for their love. This is surely a motivation for me.

clip_image002

You can find more details about book on Amazon

clip_image003

There are 9 chapters in the book and I cannot wait to start learning it. Buy this book from Flipkart here

Once again thank you so much Julie and Rowan for the impeccable gift. Last but not least I would extend thank to my friend Amit and Mahinder for bringing it for me all from USA.

Happy Coding guys !

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.

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.