Write a comment | Articles | DHTML Gallery | .NET | MyBlog | About Me | FAQ

Javascript, OOP and Reuse
View online demos | Download the javascript

Today a normal interactive page might well contain hundreds of lines of javascript code. If written improperly , they can be a nightmare to modify and reuse. With advent of AJAX applications, writing javascript is increasingly becoming a complex task and don't forget the browser inconsistencies. This is where object oriented programming comes into picture. For those who don't know, yes it is possible to do object oriented programming in javascript. This article is not a 'How to' on that topic for I am myself a learner. There are tons of articles on this topic available on the internet. Some are listed at the end of this article.

Introduction
In this article we will see how object oriented programming with javacript promotes high reuse of properly written code. We will take previously written code , make it object oriented and ourselves see what benefits we get out of it. I am taking the code for 'animated collapsible panel' written by me for this purpose. Right now the code for the panel is very procedural and depends on a couple of functions and global variables. The user has to cut/paste the HTML code in order to construct a new panel. If done improperly , our code might throw an exception. The basic complain one may have is , the entire structure of the collapsible panel is visible to the user .The user is only interested in displaying his content on the panel. There is no need for him to know that the panel is actually a table , with tow rows , upper being the title row ... I mean these things are like private information of a panel. It really does no value to the user , so long as he is not interested in modifying the behavior or look of the panel. But then, if he does want to modify the behavior or look of the panel , he might have put more global variables and functions. He also has to make sure that they are called on corresponding events of elements of panels (onclick , onchange..etc) and maybe in a particular order.Wont it be nice if all these things were taken care of automatically ? If you think yes , then read through.

Very Brief Intro to OOP in Javascript
As previously stated, this is not a tutorial on OOP with javascript. Here we will see a simple class in javascript.


function test()
{ 
var x =  new COOPPanel('a',' Panel','Hello! how are you',180,0.85,0.1,10);
//x.Collapsed(false);
x.SetIconURLs('images/plus.gif','images/minus.gif');
x.Collapsed(true);
}

function Account(no)
{var acc_number; //Private member
 var balance=0;  //Private member
 
function init() //Private function used for initialization
{ 
  if(! Account.IsValidAccNumber(accno))
  {alert("This is not a valid account number");}
}
 
 //Public functions
 this.deposit = function(amt){balance+=amt;}
 this.withdraw = function(amt){balance+=amt;}
 this.getbalance = function(){return balance;}
}
 
//Public static function 
Account.IsValidAccNumber = function(x)
{ return (x.length == 10)? true:false;}

var i= 'AB34567890' 
if( Account.IsValidAccNumber(i))//static method  of  classAccount  called
{ var  acc1 =  new Account('1234567890')  //new object of class Account created
  acc1.deposit(100);
  acc1.withdraw(21.32);
  acc1.deposit(12.42);
  alert('Balance of account '+ i + ' is ' +acc1.getbalance());
 }   
 

The syntax for declaring a class can slightly differ . One thing to note here is this is the traditional way of declaring class in Javascript. There is one more , slightly cryptic syntax using JSON . A discussion on JSON is out of scope of this article. But it is worth knowing this , especially if you stumble across some code written in that manner , which is quite possible these days . Complex OOP behavior can be obtained by using very cryptic techniques. Inheritance in javascript is not very simple to achieve and there are quite a few mechanisms of doing it. Our requirements are not complex . We will take what is required.

So, what we are looking at is a javascript that enables us to do something like this :

var mypanel = Panel("mypanel",100,100,"The Title","This is the content") ; //constructs a panel of 100x100
mypanel.Collapse(); //collapse the panel
mypanel.SetTitle("New Title"); //change title
mypanel.SetContent("New Content"); //change content
mypanel.SetCollapseSpeed(20); //Set collapse speed
mypanel.Expand();

var smallpanel = Panel("mypanel",10,50,"Small Panel","Content for small Panel") ; //
mypanel.Collapse();
mypanel.SetTitle("New Title");
mypanel.SetContent("New Content");
mypanel.SetCollapseSpeed(20);
mypanel.Expand();

//what ever you fancy.
Wont that be great ! If you know even a bit about object oriented programming , you can now tell that mypanel is an object of class Panel. Collapse , SetTitle, SetContent , Expand are public functions . If you have programmed in any modern object oriented language , you probably can now write the Panel class. But wait !. This is javascript. There are quite a few things to be considered when making such objects , apart from syntax :
  • Not all aspects of object oriented are directly supported by javascript. There are no keywords like public , private ,virtual ..etc. These behaviours have to be simulated using some syntax or mechanism.
  • There is no graphics library available for javascript. You can only use HTML as front end. So if you are planning to write a 'paint' program in javascript think again.
  • The event model for web browsers is very very constraint. To add to your troubles their implementation vary with browsers.
  • What you can do with javascript is very limited . You really cant control the performance of your script nor can you bypass restrictions imposed by the browser (like javascript can not read from file).
  • Javascript can be disabled by user on his/her browser.
  • Larger size javascript will cause your page to load slowly.
  • Last and the most important. You are required to write code that works on major browsers , considering the above 5 points ,for it to be reusable.

Its certainly no luxury or enjoyable task to do OOP in javascript. We need to live by such limitations.

Planning the COOPPanel object
COOPPanel will be similar to the panel discusses in previous article , but it will be object oriented.The most notable difference, would be that the user will not write mark up to create a new panel .That job will be done by the constructor. So the constructor will tailor the required HTML and put it to place inside a place holder of our choosing. The placeholder has to be a simple <DIV> tag with unique id. This is all the care the user has to take .
One important aspect that influences our object oriented design is , that the HTML though looks like part of the panel object , it really isn't . For example , the icon image (used for resizing) does not understand 'this' keyword in context of the logical object it is contained in. I mean , this line wont work.

<img src='resizeicon.jpg' onclick=this.OnclickHandler() ....>

The <IMG> tag is in no way associated with the particular instance of javascript object that created it. So here we need to create a 'static' function. We could have created a normal Javascript function , but a static function looks neat ! The user can create as many instances of the panel object on a single page. A clever trick here it to leave the issue of 'positioning' to the container <DIV> . If this <DIV> is relatively positioned, it will automatically make our panels positioned like that ,or otherwise absolutely positioned. So user can stack panels on on another or simple put them at fixed locations on screens (like dropdown menus).

Here is a list of features that our panel will have:
  • Fading opacity while collapsible and reverse when it restores.
  • Relative opacity for the whole panel.
  • Adjustable speed of resizing.
  • Adjustable smoothness of resizing.
  • Adjustable width using CSS class.
  • Ability to modify the contents of panel at runtime. This will be very for use with AJAX as discussed later in this article.
  • Ability to modify the style of Title, icons and content area using CSS classes.
  • Ability to modify resize icon pair. Here again there is lot of temptation to add more features.
But as I always (try to) do , get what matters most ready first.

Short Walkthrough of code
In my opinion the most important part of these demos is not what the user sees on screen but what he see after clicking on 'View Source' in his or her browser . Clean , OOP javascript. The code that does most of the trick is in the file OOPPanel.js.

The init() function is the constructor. This function creates the HTML structure required for a panel , using createElement() and appendChild() methods of DOM. The CAJAXPanel.OnTitleClick() is a static function , that does job of minimizing and maximizing the panel. This had to be made static because, it calls 'minimisepanel()' and 'maximisepanel()' functions internally, which again are static. These functions had to made static, since they are called recursively using the javascript's 'setTimeout' method. So all the important values are passed on to these functions as parameters. The code is similar to what it was for the older collapsible panel. I am not willing to discuss it in detail, right now. Important thing here is, we are still using the functions from Yahoo UI library. So our panel is dependent on the Yahoo UI Library.

How to do AJAX ?
As such there is no code for doing AJAX, inside the panel object. However it does have a 'SetContentHTML()' method.So the idea is to use any implementation for AJAX , fetch data from server and display it into the panel. In the demos, I have used Yahoo UI library's AJAX implementation. You can see the demo here.

Tiny documentation/mannual
This is very small documentation or manual I wrote for the panel. Hope you find it useful. Criticism and suggestions are always welcomed.

Method Description
CAJAXPanel(div,title,strHTML,height,
opacity,speed,smoothess)

div: The id of <DIV> being used as placeholder. It should be unqiue for every instance.

title : The title text or HTML to be displayed on the title bar

strHTML : The HTML to be displayed in the content area

height : Height in 'px' for the widget

opacity : The opacity for the control. Value should be between 0.00 and 1.00

speed : Value determines how fast the animation when collapsing should occur. The value is in milliseconds

smoothess : Atually the step , by which the panel collapses . In conjuction with 'speed' will help to control the animation.

ContainerStyle(className) Sets a new CSS class for the container <DIV> (one with unique id)
SetTitleStyle(className) Sets a new CSS class for tite area
SetContentDIVStyle(className) Sets a new CSS class for the content area.
SetContentHTML(strHTML) Sets the innerHTML(content) of content area
SetTitleHTML(strTitle) Sets the title string.
Collapsed(boolean) If b==true then panel is collapsed  else it is minimised
SetIconURLs(d,u) Sets new image URLs for maximise icon (d) and minimise icon (u).

Links

Copyright (c) 2007-2008 Ashish Patil . Please read FAQ for more details.