Tuesday, June 21, 2011

Writing Javascript in object oriented way : Namespace, Encapsulation : Public , Private , Static method

I used to develop a control which contain more than 6 tab and very tab contains control which work based on javascript functionality.My code became unmanageable and I decide to write my JavaScript code in object oriented way as I write my C# code. I found a code from codeproject for adding namespace in your code in good way.  I have share here the like of this article . http://www.codeproject.com/KB/scripting/jsnamespaces.aspx
So I created my class with name System.Classes.Placement as
registering that class in using.js
Namespace.Register("System.Classes.Placement");

and in my page
System.Classes.Placement = function () {
……
}
Now need some code public which will initialize jquery popup,  and register click handler. and also some Jquery drag drop code.
So I created functions for those function but those do not need to be public. I need only one Init() public function and CreateJqueryPopUp(), CreateDragable(), CreateDroppable() do not need to be public we can create them as private wich provide more encapsulation. So I created public public with return statement which is more readable. And other function are created before return statement.

So the function became like that
System.Classes.Placement = function () {
    var CreateJqueryPopUp =function()   {…..}
    var CreateDragable = function() {…..}
    var handleDropEvent = function(){….}
   return
  {
       init:function()
      {
        CreateJqueryPopUp ();
        CreateDragable();
      }
  };
}
and called the init() function in document ready method for initialization.
$(document).ready(function () {
            var placement = new System.Classes.Placement();            
            placement.init();
                   });
This words fine. But I also need function for deleting one item. as it would be on button click event and I do not like to create instance again for that to call RemoveItem method also I want RemoveItem method would be in that namespace. So for that I need to create a static method so that I can call this method like
onclick = "System.Classes.Placement.RemoveItem(this)"
Creating a static method is also easy. You need to define a method outside of class like
System.Classes.Placement=function(){
…..
   return{
     …
     };
}
System.Classes.Placement.RemoveItem =  function (div) {
            var parent = div.parentNode.parentNode;
            $(parent).empty();
            $(parent).removeClass('selected');
        }
So I got almost same flavor of Object oriented programing in javascript as in C# just with little convention. As much your code would be object oriented code would be more manageable.