Drive your site with a JS Singleton

Over the past years I have created far too many web sites that I can honestly recollect.  Some were great, some were not but what all of them had in common was a lot of JavaScript.  Way back in the early days and I’m talking about the 90’s, we all enthusiastically created our sites mixed in with a jumble of JS functions.  Many of us in those days thought it so cool to be doing rollover functions and preloading images with JS functions and all other sorts of funky stuff.  However, over time as sites became more complex the JS code started to look like spaghetti and was difficult to maintain.  In comes the JS Singleton to the rescue. 

Imagine you have just been handed an existing web site to do some upgrades.   You are tasked with modifying some dialog style interfaces on the site and adding some new fields to the user form. As you start to scour through the server side code and the front end html you finally dig up an onclick event something like createDialogInterfaceForm(this) bound to an HTML element.  Great you say, now you start digging through all of the JS looking for this magical function that you have found appears all over the site.  When you finally find it you discover it and it has a tonne of internal branches based on the caller which then call other functions.  Great you say, this function is used all over the place so making any modifications will result in me having to retest everywhere, so much for an easy fix. Now imagine instead, you see something like site.ui.dialog.user and to your astonishment there is only one single JS file for the site.  Hmm, you say cool. So upon opening the single JS file you are presented with the following:

var site={
      // some code
      ui:{
            dialog:{
                  user:function(){
                        var dialog=site.ui.oDialog({width:600,height:400})
                        dialog.addControl({type:’textbox’,label:’Name’)
                        // do a bunch of stuff
                        dialog.show()
                  },
                  company:function(){
                        var dialog=site.ui.oDialog({width:400,height:300})
                        dialog.addControl({type:’textbox’,label:’Name’)
                        dialog.show()
                  },
                  oDialog:function(oConfig){
                        return new dialog{oConfig}
                        function dialog(configObject){
                              this.width=500;
                              this.height=300;
                              this.show=function(){}
                              this.addControl=function(oConfig){}
                              // do a bunch of stuff
                        }
                  } // end oDialog 
            } // end dialog
      } // end ui
} // end site

Wow you say this looks complex but as you start to break it down it become apparent that it is actually fairly simple and rather convenient.  For starters all of the sites JavaScript exists within the Singleton called site. Within the site object there is a sub class entitled ui, and within that class there are several methods, user, company and oDialog.  Notice that  the oDialog method returns an object of type dialog.  Also notice that it takes a variable entitled oConfig. This in turn is an object itself which is passed to provide parameters/defaults to the class/object dialog.  What is important to note in this style of implementation is that both the user and company methods of ui rely on the common class oDialog.  It is also abundantly clear that each of the two methods in essence do the same thing but pass different config objects to the oDialog method which returns an object which is assigned to a local variable.  Notice also that since the local variable dialog in both user and company is an object it also provides methods for adding controls to the dialog before it is shown.  Wow you say to yourself, all I have to do then to add the necessary field is a single line of code in the user method.  This is of course pseudo code, but by using a singleton implementation it becomes much more evident how and where you would do you work.  Also, it allows for the simple addition of methods within a logical class structure rather than writing individual functions and struggling for a name that is evident.  In essence it’s all about elegance that provides clarity and manageability of code.  I feel that elegance is something that is sorely missing in web code these days.  When I look at what is served up by server side implementations like .NET and Java/JSP all I see is a massive jumble of poorly formatted html and script tags all over the place.  The argument is ‘well who cares it works’.  Well I care and think there is no excuse for lousy resulting source code.

So what does a singleton provide you:

  1. Elegence in code
  2. Greater maintainability
  3. More obvious method calls
  4. A clear object structure that reflects the site structure in many cases

You may be saying at this point that this may be cool but wouldn’t I just end up with a massive single piece of code and even code that I do not need for a specific page.  Well you would be correct in that assertion.  So in the next post I will discuss how to separate your singleton code out into individual class files and load on demand into the master singleton.

Regards
Keith Chadwick

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s