All posts by Thiyagu

KnockoutJS – Environment Setup

It’s very easy to use KnockoutJS in our project by Simply referring the KnockoutJS Javascript file within the <script > tag in HTML pages like other script reference. We can access the Knockout.js in different ways like below

Referring Internally:

We can download latest version of the Knockout.js from its official website and add to our solution for making reference within out project.

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

Referring Externally:

We can refer the KnockoutJS library from CDNs and this can be achieved by following way.

Refering from KnockoutJS library from Microsoft Ajax CDN like below.

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

In another way can refer to a minified version of KnockoutJS library from CDNJS as below:

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

 

What do you think?

I hope you have idea of how to setup KnockoutJS in our Application. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

Knockout VS jQuery

Need to compare Knockout with jQuery?

Actual answer for above question is “NO”. Knockout.js is not a replacement of jQuery, Prototype etc.,. It doesn’t target to provide animation or AJAX functionality (Knockout.js can parse the data which received from an AJAX request). Knockout.js is focused only designed on data-driven UI. It is compatible with other client-side and  server-side technology.

Knockout.js uses a Model-View-ViewModel (MVVM) design pattern. In this, the model is react as data from back-end/business logic and the view is the visual representation of that data (UI) which is visible to the user and ViewModel acts as the intermediary between the model and the view.

In simple we can say the ViewModel is a JavaScript representation of the model data, along with associated functions for manipulating the data. Knockout.js creates a direct connection between the ViewModel and the view, which helps to detect changes from the mode and automatically update to the all the required changes in UI, in same way the update made in UI will automatically update to the model by the help of view model.

How to use Knockout ?

Simply reference to be made for the knockout file using a <script> tag in our your HTML pages. Let see below example,

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

What is Knockout.js and how is it differ from jQuery?

What is Knockout JS?

Knockout is a JavaScript library that helps you to create rich, responsive UI and with clean data model. In other word, It is a javascript library that allows us to bind html elements against any data model. It provides a simple two-way data binding mechanism between our data model and UI.

Why Knockout?

The User interface(UI) data section will update dynamically when any changes had updated by user’s action or any external data update the Knockout is the best solution for simple to handle it. Its provide a simple mechanism to handle out data model and UI. For example if any changes made on data model are automatically it will reflect in the DOM(User Interface) and if any changes to on the DOM will automatically reflected to the data model.

With Simple Real time example

Let we discuss about with simple shopping cart Interface. If user add an item in the shopping cart, then it need to have to add the items from the data model and add the associated html element to the shopping cart. Finally the total price need to update in the UI. Consider the same scenario for the delete operation, same need to be update in all the scenario. So if we are not using knockout for doing this, then we need to write event handlers and listeners for dependent.

Let we conclude, the knockout will track all dependencies between the HTML and their underlying data and update dynamically(automatically) when update has made by user or from the back-end (update made by system side).

How is Knockout differ?

We all loves jQuery for its excellent way to manipulate elements and event handlers in a web page. But KO is solves a different problem. It is not a replacement of jQuery or other framework. It not target to provide animation, AJAX functionality or generic event handling. It is focused only on designing salable and data-driven interface.

Knockout js Features

KnockoutJS was developed and is maintained as an open source project by Steve Sanderson, a Microsoft employee on July 5, 2010. KO is basically a library written in JavaScript, based on MVVM pattern that helps developers build responsive and rich websites. The model separates the application’s Model, View (UI) and View Model (JavaScript Representation of model). Let we discuss about features of KO.

Features of KnockoutJS

Elegant Dependency Tracking

Knockout automatically updates the right parts of your UI whenever your data model changes. You no need to worry about adding event handlers and listeners for dependency tracking like in Jquery.

Extensible

This implements custom behaviors as new declarative bindings for easy reuse in just a few lines of code. KnockoutJS is independent of any other framework and it is compatible with other client or server side technologies.

Templating

Knockout can use alternative template engines for its template binding. Knockout has a native, built-in template engine which you can use right away and can be customize how the data and template are executed to determine the resulting markup.

Benefits of KO

If we implement KO with your web application then we can get the following benefits:

  • Easily we can create complex dynamic data model.
  • Anytime we can connect UI elements with data model which is synchronized.
  • Automatically UI will update when Data Model is changed. If any UI changed by user or in back-end then Data Model will change automatically.
  • It support event-driven programming model.
  • It mainly support all the browsers(Internet Explorer, FireFox, Crome, Safari).

KO with MVVM

What is MVVM?, the full form of MVVM is Model View ViewModel. It is an architectural design pattern designed by Microsoft and mainly created for WPF/Silverlight applications. KO builts on MVVP architectural design pattern. So if you want to understand KO properly, then you should know about MVVM.

Overview of MVVM:

MVVM stands for Model,View, ViewModel.

Model: Responsible for holding Application data. In simple, its refers either to a domain model or to the data access layer, which represents content

View: Responsible for presenting model data to the user. Its nothing but a User Interface which is getting information from the user.

ViewModel: Connector of Model and View. Main responsibility is to establish communication with View and Model. It holds data and function.Functions manipulate that data and it reflect to the UI. When data is changed in UI by the user, then data will be changes.If data is changed by the back-end then the UI will change accordingly. ViewModel will do it for us with the help of data-binding concept.

knockout js mvvm

practice knockout

MVVM Benefits

  • Provide more flexibility of designer and developer works.
  • The ViewModel is easier to unit test than code-behind or event-driven code.
  • Provide flexibility to change user interface without having to re-factor other logic of the code base
  • The presentation layer and the logic is loosely coupled.

Difference between Abstract Classes and Interfaces

Difference between Abstract Classes and Interfaces

Abstract  Interface
Abstract class can have abstract and non-abstract methods                                                  . Interface can have only abstract methods and abstract class can have field/property but interface not allow it.
Abstract class doesn’t support multiple inheritance Interface supports multiple inheritance.
It can use access modifier But interface wont have it because within an interface by default everything is public
It can have final, static ,non-final and non-static variables Interface has only final variables and static
It can provide the implementation of interface Interface can’t provide the implementation of abstract class

 

Let us discuss the difference one by one with simple example.

Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods and abstract class can have field/property but interface not allow it.

Abstract Class:

public abstract class Employee
{
public string FirstName;
public string LastName;

public override int GetFullName()
{
return this.FirstName + " " + this.LastName;
}
}

Interface : Wrong

public interface IEmployee
{
// Cant use field in interface
public string FirstName;
public string LastName;

//Implementation & access specifier will not accept
public int GetFullName()
{
return this.FirstName + " " + this.LastName;
}

}

Interface : With Proper

public interface IEmployee
{
void GetFullName();
}

Note : In simple, An abstract class can has implementation or non-implemented methods but interface can’t have implementation for any of its method.

Abstract class doesn’t support multiple inheritance. Interface supports multiple inheritance.

It’s not possible to inherite more than one abstract class. For example, if we having two abstract class namely Employee , EmployeePersonalDetails.

Abstract: Error

//Multiple class can't be inherit. 
class PartTimeEmployee : Employee ,EmployeePersonalDetails
{
... code here....
}

Interface: It support multiple inheritance

class PartTimeEmployee : IEmployee ,IEmployeePersonalDetails
{
... code here....
}

 An abstract class can access modifier but interface wont have it because within an interface   everything is public in default.

Interface : Incorrect

public interface IEmployee
{
public void GetFullName();
}

Interface : Correct

public interface IEmployee
{
void GetFullName();
}

 

 

Abstract class vs Concert Class

In most of the interviews, we face the struggle to explain the scenarios for the concrete, abstract & interface classes. This leads to the interviewer to have bad impression.

Why we are moving to the abstract instead of Concrete class?

When should we use concrete, abstract, interface?

After these types of questions, we will get bit confused to answer. So in this post, we are going to discuss ‘how’ and ‘where’ to use the concrete and abstract classes.

Requirement:

Let us consider that a company requires the details like full name, salary details etc., of their employees working full time and part time. Based on the above requirement, let us create the two classes like FullTimeEmployee, PartTimeEmployee as shown below.

FullTimeEmployee Class

class FullTimeEmployee : AbstractBaseClass
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int YearlySalaray { get; set; }

public string GetFullName()
{
return this.FirstName + " " + this.LastName;
}

public override int GetMonthlySalary()
{
return this.YearlySalaray / 12;
}
}

PartTimeEmployee Class

class PartTimeEmployee : AbstractBaseClass
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int HourlySalaray { get; set; }
public int TotalHour;

public string GetFullName()
{
return this.FirstName + " " + this.LastName;
}

public override int GetMonthlySalary()
{
return this.TotalHour * this.HourlySalaray;

}
}

Disadvantage:

From the above two classes, we are able to get the details from both type of employees by creating instances of those.But we can observe that there are many repeated properties and methods presented in both classes like FirstName, LastName, GetFullName(), GetMonthhlySalray() . To avoid these type of redundancies, now we are going to create one more class called BaseEmployee to handle the common properties and methods.

Concrete Classes:

A Concrete class is a normal class so we can use it as a base class (optional), it cannot contain abstract methods.

Based on the above conclusion, the common properties and methods have moved the class called BaseEmployee. The GeMonthlySalary() method need to be declared as virtual because the BaseEmployee class doesn’t know how to provide the implementation for both the FullTimeEmployee & PartTimeEmployee classes because it is calculating the salary based on the employee’s type.

When to use?

Base class might be best option when all of your child classes can share the same implementations of the members on the base class.

BaseClass:

class BaseEmployee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public string GetFullName()
{
return this.FirstName + " " + this.LastName;
}

public virtual int GetMonthlySalary()
{
throw new NotImplementedException();
}

}

FullTimeEmployee Class

class FullTimeEmployee : BaseEmployee
{

public int YearlySalaray { get; set; }

public override int GetMonthlySalary()
{
return this.YearlySalaray / 12;
}
}

PartTimeEmployee Class

class PartTimeEmployee : BaseEmloyee
{
public int HourlySalaray { get; set; }
public int TotalHour;

public override int GetMonthlySalary()
{
return this.TotalHour * this.HourlySalaray;
}
}

If we create an instance of both classes, then application will run without any error and give results. Still we are having some disadvantages of using concrete Classes and those are mentioned below

Disadvantage:

1) There is nothing that stops us from creating an instance for the Baseclass.
2) If we access the non-defined method in the base class, then it will throw the error at runtime using instance. To overcome these types of issues, we are moving to the abstract class

EG: BaseEmployee baseEmp = new BaseEmployee()

baseEmp.GetMonthlySalary()

Abstract Class:

The Abstract class is a special / incomplete type of class, which cannot be initiated and it acts as a base class for other derived classes. An Abstract method must be implemented in the non-Abstract class using the override keyword. The method that is declared as abstract needs to be implemented by derived classes.

When we use the abstract class?

We can use abstract class when we want to move the common functionalities of two or more related classes in to the base class and we don’t want the base class to initiate.

Let us create the “AbstractBaseClass” instead of concrete Base class as shown below. The “GetMonthlySalary()” is declared as abstract so we no need to provide the implementation. So within the derived class, we are going to provide the implementation by overriding it.

abstract class AbstractBaseClass
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public string GetFullName()
{
return this.FirstName + " " + this.LastName;
}

public abstract int GetMonthlySalary();

}

FullTimeEmployee Class

class FullTimeEmployee : AbstractBaseEmployee
{

public int YearlySalaray { get; set; }

public override int GetMonthlySalary()
{
return this.YearlySalaray / 12;
}
}

PartTimeEmployee Class

class PartTimeEmployee : AbstractBaseEmloyee
{
public int HourlySalaray { get; set; }
public int TotalHour;

public override int GetMonthlySalary()
{
return this.TotalHour * this.HourlySalaray;
}
}

Note:

  • An abstract class can contain either abstract methods or non-abstract methods.
  • Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
  • The access modifier of the abstract method should be same in both the abstract class and its derived class.
  • An abstract class cannot be a sealed class.
  • An abstract method can’t be private and static.

.insertAfter() method in Jquery

Description:

The jQuery insertAfter() methods is used to add the contents after the selected elements.

Syntax

  • $(selector).insertAfter(target)

Difference between jQuery after() and insertAfter() 

The main difference between after() and insertAfter() method is their syntax and their placement of the target and content location.

  • after(): $(selector).after(content)
  • insertAFter : $(content).insertAfter(selector)

Example: 

<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
 <style>
 .container {
 border: 5px solid #1a80b6;
 padding: 10px;
 display: inline-block; 
 }
 </style>
 <script type="text/javascript">
 $(document).ready(function () {
 $('#btnClick').click(function () {
 $('<div style="color:#ff0000"> This is Newly added text </div>').insertAfter("#divcontainer");
 })
 });
 </script>
</head>
<body>
 <button id="btnClick">Click to Add content using insertAfter()</button><br /><br />
 <div id="divcontainer" class="container">
 <div>
 This is Default text
 </div>
 </div>
</body>
</html>

Output: 

By clicking the button, “this is Newly added text” will append after the selected div (divcontainer).

.before() method in Jquery

Description:

The jQuery before() method is used to insert content before the selected element.

Syntax

  • $(selector).before(content)
  • $(selector).before(content, function(index))  
Content It specifies the content which need to append.
Function(index) It specifies the function that returns the content which used to insert.

index: Get the index position of the element in the set

Passing Function:

.before() supports passing a function that returns the elements to insert like as below. It can accept any number of additional arguments like prepend(), after().

 $("#divcontainer").before(function () {
     return "<div>Welcome to Dotnet-helpers.com</div>";
  });

Example: 

<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
 <style>
 .container {
 border: 5px solid #1a80b6;
 padding: 10px;
 display: inline-block; 
 }
 </style>
 <script type="text/javascript">
 $(document).ready(function () {
 $('#btnClick').click(function () {
 $("#divcontainer").before('<div style="color:#ff0000"> This is Newly added text </div>');
 })
 });
 </script>
</head>
<body>
 <button id="btnClick">Click to Add content using before()</button><br /><br />
 <div id="divcontainer" class="container">
 <div>
 This is Default text
 </div>
 </div>
</body>
</html>

Output: 

By clicking the button, “this is Newly added text” will append befor the selected div (divcontainer).

.after() method in Jquery

Description:

The jQuery after() method is used to insert content after the selected element.

Syntax

  • $(selector).after(content)
  • $(selector).after(content,function(index))
Content It specifies the content which need to append.
Function(index) It specifies the function that returns the content which used to insert.

index: Get the index position of the element in the set

Passing Function:

.after() supports passing a function that returns the elements to insert like as below. It can accept any number of additional arguments.

 $("#divcontainer").after(function () {
     return "<div>Welcome to Dotnet-helpers.com</div>";
  });

Example: 

<html>
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
 <style>
 .container {
 border: 5px solid #1a80b6;
 padding: 10px;
 display: inline-block; 
 }
 </style>
 <script type="text/javascript">
 $(document).ready(function () {
 $('.btnClass').click(function () {
 $("#divcontainer").after('<div style="color:#ff0000"> This is Newly added text');
 })
 });
 </script>
</head>
<body>
 <button id="addMethod">Click to Add content as First Child</button><br /><br />
 <div id="divcontainer" class="container">
 <div>
 This is Default text
 </div>
 </div>
</body>
</html>

Output: 

By clicking the button, “this is Newly added text” will append after the selected div (divcontainer).

 

.prependTo() method in Jquery

Description:

The Jquery prependTo() method is used to add additional content at the beginning of the selected elements. It is same like as prepend() method, it will add content as the first child of the selected elements. The main difference is their syntax-specifically, in the placement of the target and content location.

Syntax

  • $(content).prependTo(selector)

Example: 

<html>
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
 <style>
 .container {
 border: 5px solid #1a80b6;
 padding: 10px;
 display: inline-block; 
 }
 </style>
 <script type="text/javascript">
 $(document).ready(function () {
 $('.btnClass').click(function () {
 $('<div style="color:#ff0000"> This is Newly added text</div>').prependTo("#divcontainer");
 })
 });
 </script>
</head>
<body>
 <button id="addMethod">Click to Add content as First Child</button><br /><br />
 <div id="divcontainer" class="container">
 <div>
 This is Default text
 </div>
 </div>
</body>
</html>

Output: