JavaScript Day : Presented on Arrays in JavaScript

Hi All,

We had organized again a very successful event at C# Corner Delhi Chapter meet fifth times in a row. This was named as JavaScript Day and attended by more that 120 attendees . The entire day we discussed on Core JavaScript and we’ll cover more topics in coming monthly meet.

I discussed on JavaScript array and covered the following topics.

Continue reading

Bind a CheckBox list from database using jQuery AJAX

Hi All,

I have seen many questions in the forums that how can we bind the CheckBox list from the database via Ajax. There could be many ways to do in an ASP.NET but I will be using the one of the most efficient options available .

In this post, I’ll be using jQuery Ajax to get the data from the server (that will be fetch the data from database) and then will create the CheckBox list dynamically.

Continue reading

How to consume wcf service using JavaScript Proxy

Hello All,

Today I am going to discuss one another great feature of WCF. Do you know that a WCF service allows us to create a JavaScript Proxy?

Yes it does!!

But let’s first understand that what is a proxy? As we already know whenever we have to use any web service or WCF service, we need to create proxy of that service and with the help of proxy, we use the functionalists provided by the web/WCF service.  Proxy acts a intermediary between the client of the service and the actual service. Proxy provides a simple interface to the consumer of service and all the intricacies like creating a connection, creating and sending the request, getting the response etc is handled by the proxy itself.

Continue reading

Presented on ASP.NET MVC and AJAX at C# Corner Delhi Chapter event

Hi All,

Again we had a very successful event at C# Corner Delhi Chapter July meet on 20the July. This time again despite bad weather, it was attended by more that 100 attendees and we discussed a list of hot technologies. This time Mahesh Chand sir, the founder of C# Corner was also present and discussed about Enterprise architecture.

Continue reading

document.ready vs Javascript onload

It is a small post, who are new to jQuery or just started working with jQuery. As we all know that jQuery is Client side library and provides a wrapper over JavaScript . One of the very good things about jQuery that it runs seamlessly in all leading browsers while you must have faced many issues related to the browsers when you work with JavaScript.

So let’s jump to the topic. What is the difference between let’s first go by an example.

I have created a simple default.aspx page in my asp.net empty application and added few images and put the path from web and added few text. Now I put a general alert and called it on load method of window as

<script type="text/javascript" language="javascript">
        window.onload = OnLoad();
        function OnLoad() {
            alert('I am called by window.onload');
        }
    </script>

Now again I tried to change the code to jQuery document.ready function. And used the code as

$(document).ready(function () {
              OnLoad();
         });
        function OnLoad() {
            alert('I am called by document.ready');
        }

and when I ran it. I got the alert very fast. So what I wanted to point out here that jQuery’s document.ready runs much earlier the JavaScript onload. Why?

document.ready get’s fired as soon as DOM is ready and registered with the browser. It does not wait for the all the resources to get loaded. It allows us some very cool showing, hiding and other effects as soon as user sees the first element on the page.

While Javascript’s onload method gets fired only when all content of the webpage and image, iframes etc get loaded in browser then onload get’s fired.

So do we have a method in JavaScript that works in similar way as document.ready?

Partially yes.

We have a method called DOMContentLoaded  that is actually called by jQuery from document.ready. But that’s not it.  DOMContentLoaded is not available to every browser and versions. For IE > 9,  onreadystatechange works in the same way. In case nothing works in browser, jQuery has a fallback and it implemented own logic to traverse the DOM and check the when the DOM got registered and fires document.ready accordingly.

So I hope you all got to know the basic difference between these two.

Cheers,
Brij

HTML5 : Set multiple audio/video files dynamically and run one by one

One of my blog Reader was working on HTML5 audio controls. He asked me a question How can he play multiple audio files one by one. And his requirement was to set the audio files dynamically. So I thought of sharing the solution here. You can customize based on your requirement.

So what I have done. I created an audio control as

 <audio id="ctrlaudio" controls="controls" runat="server">
                Your browser does not support the audio tag.
 </audio>

As you can see an Audio control and made it as runat server, So that I can set some values from code behind. I have also created a hidden variable to set the comma separated name of songs that I want to run one by one. In my code behind I am setting a source for this audio control. My code behind as

string innerHTML =
            "<source src='song1.mp3'></source>";
        ctrlaudio.InnerHtml = innerHTML;
        hdnSongNames.Value = "song1.mp3" + "," + "song2.mp3";

So the whole logic is written in JavaScript and I have used jQuery as well. The logic is something like, First get the list of song names using hidden variable that I require to run one by one . Then I attached an event ended to the audio control. This event is fired when the current playing song is ended. And when one song ended and other next song starts playing. Let’s see the code

 $(function () {
            //Find the audio control on the page
            var audio = document.getElementById('ctrlaudio');
            //songNames holds the comma separated name of songs
            var songNames = document.getElementById('hdnSongNames').value;
            var lstsongNames = songNames.split(',');
            var curPlaying = 0;
            // Attaches an event ended and it gets fired when current playing song get ended
            audio.addEventListener('ended', function() {
                var urls = audio.getElementsByTagName('source');
                // Checks whether last song is already run
                if (urls[0].src.indexOf(lstsongNames[lstsongNames.length - 1]) == -1) {
                    //replaces the src of audio song to the next song from the list
                    urls[0].src = urls[0].src.replace(lstsongNames[curPlaying], lstsongNames[++curPlaying]);
                    //Loads the audio song
                    audio.load();
                    //Plays the audio song
                    audio.play();
                    }
            });
        });

As I have made a comment on most lines of the code, I don’t need to explain it again here. One point, I want to make it here that I have done some coding at Code behind you can totally do at Client side only. If you need any details from server, can initiate a Ajax call get the details (here list of songs) .

Also, the video tag also works similar to audio tag. So you can work similarly with video tag also.

So you can use your business logic.

Hope you all have enjoyed this.

Cheers,
Brij

Inheritance with JavaScript

This post is in continuation in my last post.  In my last post, I discussed various ways to create custom object in JavaScript. I’ll advise you to go through that if you didn’t get a chance to have a look then you can go through it. Please find the link below

Various ways to Create custom objects in JavaScript

In this post, We will discuss, how we can use other features of Object Oriented concepts in JavaScript. Today I’ll discuss one of the main concepts of Object Orient Programming that is Inheritance.

So how can we use Inheritance with JavaScript ?

Various ways and plugins are available that provides similar ways to use Inheritance that we have used in other object oriented language. But the prototype based Inheritance is used most.

JavaScript is a object based language that is based upon Prototype based programming. It is free from Class and completely rely on objects only .

Did you hear earlier  that What is Prototype based language or what is Prototype based programming?

I would say this is just another way to provide object oriented feature by a language. As per wiki

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming”.

So let’s start learning. To create a Class in JavaScript, we are required to create a function  that we also used to call a Constructor. I’ll use the word constructor in my further discussion. So Let’s create a Constructor called person

         function Person() {
             this.ToString = function () { alert('I am a Person'); }
             this.DisplayResidence = function () { alert('I stay near my office'); }
         }

As in my last post, I mentioned that Person is a nested function. As you can see that here we have following two functions in the Person constructor.

  1. ToString
  2. DisplayResidence

So let’s create a new object and display it

function DisplayObject()
{
var objPerson = new Person(); // Line- 1 Creates the instance of Person
objPerson.ToString();  // Line- 2
objPerson.DisplayResidence(); // Line- 3
}

Here both display as expected . Line 2 - I am a Person and Line 3 - I stay near my office

Now let’s say we want to create a constructor Employee as

         function Employee() {
             this.ToString = function () { alert('I am an employee'); }
             this.DisplayRole = function () { alert('My role is development and implementation'); }
         }

As you can see it has two methods ToString and DisplayRole. Now how can Employee inherit the properties/methods of Person. It can be done by writing as

Employee.prototype = new Person();

Now the employee has the properties of person as well. Now it has three methods

  • ToString()
  • DisplayResidence()
  • DisplayRole()

Let’s examine it by the method

         function DisplayObject() {
                var objPerson = new Person(); // Line- 1: Calles constrouctor Person to create an instance and assign it to objPerson
                objPerson.ToString(); // Line- 2: Calles ToString method of Person
                objPerson.DisplayResidence(); // Line- 3: Calles ToString method of Person

                var objEmployee = new Employee();  // Line- 4: Calles constrouctor Employee to create an instance and assign it to objEmployee
                objEmployee.ToString(); // Line- 5: Calles ToString method of Person
                objEmployee.DisplayResidence(); // Line- 6:  Calles ToString method of Person
                objEmployee.DisplayRole(); // Line- 7:  Calles ToString method of Person

                alert(objPerson instanceof Person);  // Line- 8:  Checks the type of objPerson
                alert(objEmployee instanceof Person);  // Line- 9:  Checks the type of objEmployee
         }

Let’s discuss it by Line numbers

Line 2 and Line 3- same as discussed above

Line 5- What it will display ? It displays I am an employee because ToString is available at both current and parent. But because the objEmployee holds the instance of derived class so the overridden method is called.

Line 6- Here DisplayResidence is not defined in Employee so it calls the base class(Person) method and displayed.

Line 7-  DisplayRole is added in Employee object only and it shows ‘My role is development and implementation‘.

Line 8 – To check more on the type I added the last two lines. As objPerson is instance of Person only so it shows true.

Line 9 – As Employee inherits Person so it also shows true but if you delete the below line ….

<br />Employee.prototype = new Person();<br />

then it’ll show false as it does not inherit person any more.

Now you must have got enough Idea about prototype based inheritance in JavaScript.

There is one more way to add a method to and existing constructor as Person has two methods and  that we defined as nested class. You can write that in the following way as well

         function Person() {
         }
         Person.prototype.ToString = function () { alert('I am a Person'); }
         Person.prototype.DisplayResidence = function () {alert('I stay near my office');}

Now the question arises,  how Inheritance works in JavaScript.

Whenever we create an instance using the new Operator, It creates all the properties/methods and also has internally a variable called __proto__ (double underscore at both side) this is the variable which is responsible for the inheritance feature. So let’s say I created a instance of Employee as

var objEmployee = new Employee();

It’ll be having two methods/properties as defined and on __proto__ as

  1. ToString
  2. DisplayRole
  3. __proto__

Just because I have written also as

Employee.prototype = new Person();

The __proto__ variable gets assigned to the person instance. This __proto__ used to determine the prototype chain and return the property values. This allows us to access the base class methods and public properties.

As I talked about prototype chain, means as soon as I assign

Employee.prototype = new Person();

a __proto__ variable gets available to us that can be be further used for inheritance. So lets create another constructor as

         function TeamLead() {
             this.ToString = function () { alert('I am a Manager.'); }
             this.DisplayRole = function () { alert('I rarely code but do lot of code reviews'); }
             this.DisplayMeetings = function () { alert('I have 3 meetings scheduled daily'); }
         }

Now as soon as I’ll create an instance using new operator then instance will be have the properties

  1. ToString
  2. DisplayRole
  3. DisplayMeetings
  4. __proto__

Now if we write the code for inheritance as

TeamLead.prototype = new Employee();

It can access all the properties in the hierarchies. We can check the type of instances as

 function DisplayObject() {
             var objTeamLead = new TeamLead();
             alert(objTeamLead instanceof Person);  // returns true because TeamLead inherits base class Person
             alert(objTeamLead instanceof Employee);  // returns true because TeamLead inherits  base class Employee
             alert(objTeamLead instanceof TeamLead); // returns true as expected
             }

You can see the results and they are expected

Let’s see the prototype chain as discussed earlier

         function DisplayObject() {
             var objTeamLead = new TeamLead();

             // Also here I'll show, How the prototype chain works
             alert(objTeamLead.__proto__ == TeamLead.prototype); // returns true because it represents the same prototype
             alert(objTeamLead.__proto__.__proto__ == Employee.prototype);  // returns true because second level __proto__ belongs to Employee.prototype
             alert(objTeamLead.__proto__.__proto__.__proto__ == Person.prototype);  // returns true because third level __proto__ belongs to Employee.prototype
         }

As you can see that actually __proto__ variable is actually the key for the inheritance.

Now you all must have got enough Idea about Prototype based programming and how we can use inheritance with JavaScript.

Do share your feedback.

Happy Coding,
Brij

Various ways to Create custom objects in JavaScript

Hi All,

Many developers still put their data at client side in multiple variables and some times it becomes very tough to manage them. If we store the data in object format then it becomes very easy to manage and control it. We can have similar model as we use at server side, it provides consistency of the data model in our application.

So today we’ll see various ways to store the data in Object format at Client side.

A Simple way:

We can create a normal object and can encapsulate related data in a single object. To create  a simple object, you just need to assign a variable with new Object() and create the properties according to our requirement and assign the values as

 var person = new Object();
 person.FirstName = "Brij";
 person.LastName = "Mishra";
 person.Age = 27;

This is a simple object with few properties like FirstName, LastName and Age. You can read the object as

function displayObject() {
      alert(person.FirstName + " " + person.LastName);
      alert("Age: " + person.Age);
}

Here as you can see it is an object which contains the details of an person but here we didn’t define any class (as we do in C#) then we create an object assign some values in that. But we just created a object and created properties on the fly. Now obviously, while reading the object, you  might not get any intellisense on some editor and we need to remember the name of the properties. And if we wrongly typed the property name then we’ll get an error at run time.

Because JavaScript is loosely coupled language. There is no way if we create similar object and check whether they are similar type of object. Also it is impossible to identify  the object that you are using is actually of what type.

But there are more standard ways to Create a Type. We’ll discuss in coming section. First, we are going to discuss

Closure
Closure is function that encapsulate a class. Actually closure is not a normal function but it contains other functions and you can say it is a nested function. Inner functions actually constitutes its properties and methods. It provides an elegant way to create multiple instances of a type like person. It provides exactly similar behavior like class and object. Let’s create a closure

        function Person(fisrtName, lastName, age) {
            var _firstName = fisrtName;
            var _lastName = lastName;
            var _age = age;

            this.set_FirstName = function (fisrtName) {
                _firstName = fisrtName;
            }
            this.get_FirstName = function () {
                return _firstName;
            }
            this.set_LastName = function (lastName) {
                _lastName = lastName;
            }
            this.get_LastName = function () {
                return _lastName;
            }
            this.set_Age = function (age) {
                _age = age;
            }
            this.get_Age = function () {
                return _age;
            }
        }

Now let’s use the person and person instantiate it. As you can see that it is taking three parameters, fisrtName, lastName and age. So you need pass the values while instantiating it. Using it, you can create an instance similar like C# as

function DisplayClosure() {
        function DisplayClosure() {
            var person = new NewPerson("Brij", "Mishra", 27);

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());

            person.set_FirstName("Rahul");
            person.set_LastName("Khanna");
            person.set_Age("30");

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());
        }

So you can see, How I created instance. I have created a setter and getter to set and get the properties.

Lets’s discuss another way.

Prototype:

Prototypes provides another way to create custom objects in JavaScript. Every JavaScript object has public prototype property . This actually exposes the public interface of the object. Using this feature, we can add some public properties and methods to a JavaScript object. Let’s see it with example

        Person = function (firstName, lastName, age) {
            this._firstName = firstName;
            this._lastName = lastName;
            this._age = age;

            Person.prototype.set_FirstName = function (firstName) {
                this._firstName = firstName;
            }
            Person.prototype.get_FirstName = function () {
                return this._firstName;
            }
            Person.prototype.set_LastName = function (lastName) {
                this._lastName = lastName;
            }
            Person.prototype.get_LastName = function () {
                return this._lastName;
            }
            Person.prototype.set_Age = function (age) {
                this._age = age;
            }
            Person.prototype.get_Age = function () {
                return this._age;
            }
        }

So you can see that person is assigned to a function which is actually also a nested function but it is uses prototype property of an object. Lets instantiate it and check it.

function DisplayClosure() {
        function DisplayClosure() {
            var person = new NewPerson("Brij", "Mishra", 27);

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());

            person.set_FirstName("Rahul");
            person.set_LastName("Khanna");
            person.set_Age("30");

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());
        }

So you can see that this also is used in the similar way as Closure.
So what are the benefits of prototypes over closure. There are many..

  • Prototypes provide better support for Intellisense and debugging.
  • Prototypes also provide better performance in several browsers.
  • Prototypes support reflection and that’s why used a lot in ASP.NET AJAX.
  • Closure does not create an instance, it just specialized members to your object. instanceof does not work with Closure. While Prototype configured once then copied to every instance created using new.

Hope you all like it.

Cheers,
Brij

Playing with List Controls using jQuery

You all must be knowing, I am fan of jQuery. The kind of neat and clean code and the power provided by jQuery at Client side scripting is unmatchable.

List Controls are one of the most used form controls. And we all know that manipulating these controls from JavaScript always have been a tough task.

In this post I’ll be discussing about accessing List controls and manipulating it with the help of jQuery. Hope you all like it and also will able to apply with other controls as well.

Continue reading