Friday, June 13, 2008

Javascript and design patterns(100)

Javascript is one of the most popular and widely used languages in the world today.Because it is embedded in all modern browsers, t has an extraordinarily wide distribution. As a language, it is incredibly important in our daily lives, powering the websites that we go to and helping the web to present a rich interface. Why then do some still consider it to be a toy language, not worthy of the professional programmer? I think it is because people do not realize the full power of the language and how unique it is in the programming world today.Javascript is a very expressive language, with some features that are uncommon to the C family of languages. In this blog and subsequent ones , i will be looking at how the langauge allows you to accomplish the same task in a number of different ways and how you can take alternative approaches to object-oriented programming by using concepts from function programming.The truth is you can apply design pattern concepts in your Javascript programming. In a couple of articles that follows i will be discussing briefly the following design patterns as it concerns javascript with functional example to give you a concrete example of each of them:
The Factory pattern
The Bridge pattern
The Composite pattern
The Facade pattern
The Adapter pattern
The Decorator pattern
The Flyweight pattern
The Proxy pattern
The Observer pattern
The Command pattern
The Chain of Responsibility pattern
Keep a date with me while a take you through the world of javascript design patterns

The Factory pattern (101)

The simplest way to create new objects is to use the new keywords and a concreate class. The extra complexity of creating and maintaining a factory only makes sense in certian situations, which are outlined in this section.

If you need to create objects with the same interface but different implementations, a factory method or a simple factory object can simplify the process of choosing which implementation is used. This can happen implicitly in Ajax request where the type of connection object created depends on factors such as the percieved bandwidth and network latency. In these situations, you usually have a number of classes that implement the same interface and can be treated identically. In Javascript this is the most common reason for using the factory pattern.
Many Small Objects in one Large Object
A factory method can be useful for creating an object that encapsulates a lot of smaller objects. As an example , consider the constructor for a biycicle objects. A bicycle is comprised of many smaller subsystems;wheels, a frame, a drive train, brakes. If you do not want to tightly couple one of those subsystems to the lager object, but instead want to be able to choose one out many subsystems at run-time, a factory method is ideal. Using this technique, you could create all of the bicycles with a certain type of chain on one day, and change that type the next day if you find one that is better suited to yyour needs. Making this changes is easy because the bicycles do not depend on a specific type of chain in their constructor.

Example:(Ajax request Example)
A common task in any web page these days is to make an asynchronious request using Ajax. depending on the user's browser, you will have to instatiate one of several different classes in order to get an object that can be used to make a request. If you are making more than one Ajax request in your code, it makes sense to abstract this object creation code into a class and to create a wrapper for the different steps it takes to actually make the request. A simple factory works very well here to create an instant of either XMLHttpRequest or ActiveXObject, depending on the browser's capabilities:
Code
/* SimpleHandler interface. */

var SimpleHandler ={
request:function( method , url , calback , postVars)
{
var self=SimpleHandler;
/* This calls the factory method createXhrObject
* to return an instant of the request handler
* depending on the kind of browser the
* client is using
*/
var xhr=self.createXhrObject();
xhr.onreadystatechange=function()
{
if(xhr.readyState!==4) return;
(xhr.status==200)?
callback.success(xhr.responseText):
callback.failure(xhr.status);
};
xhr.open( method , url , postVars);
if(method !=='POST') postVars=null;
xhr.send(postVars);
},
/* The factory method that create an
* instant of the request object
* depending on the browser type
*/
createXhrObject:function()
{
var methods=[
function(){return new XMLHttpRequest();},
function(){ return new ActiveXObject('Msxml2.XMLHTTP');},
function(){ return new ActiveXObject('Microsoft.XMLHTTP');}
];
for(var i=0 ; var len=method.length ; i<>
{
try
{
methods[i]();
}
catch(e)
{
continue;
}
/* if we get to this point, methods[i] worked */
var self= SimpleHandler
self.createXhrObject= methods[i];
return methods[i];
}

/* if we get to this point anyway, none of the methods worked */

throw new Error('Simplehandler: Could not create an Ajax request handler');
},

}
To use this factory example you need to know the method of request, whether POST or GET,
the url you will be sending you request to, the data you want to send to the server,
the callback function that handles response from
the server. Now the callback function is actually an object with two functions namely, success and fialure
It is usually defined as follows
var callback={success:function(responseText){alert('Success: ' + responseText);},
failure:function(statusCode){alert('Failure ' + statusCode);
};
So to do the actual request you do this

SimpleHandler.request(method , url , data);
This simple call first, gets the parameters you want to send to the server, the url to send it to,
the method of sending POST or GET, it then internally determines the type of browser you are using in order to instantiate the correct request handler for the transaction.
an instance of XMLHttpRequest object indicate that you are using a browser that support the geko engine (Firefox,Safari,Apple etc). An instance of ActivexObject with the Msxml2.XMLHTTP parameter indicates that you are using the latest microsoft browser app- IE 7.0 and an instance of ActiveXObject with parameter Microsoft.XMLHTTP indicates that you are using version of IE less than 7.0
The convinience method request performs the steps needed to send off a request and process the reponse. it creates an XHR object, configures it ans sends the request. The interesting part is the creation of the XHR object. The factory method createXhrObject returns an XHR object based on what is available in the current environment. The first time it is run, it will test three different ways of creating an XHR object, and when it finds one that works, it will return the object created and overwrite itself with the function used to create the object. This new function becomes the createXhrObject method. This techniques , can be used to create functions and methods that store complex calculations so that they do not have to be repeated. All of the complex setup code is called once, the first time the method is executed, and after that only the browser-specific code is executed. This is a form of caching technique on the client side that utilizies the browser specific codes only for optimised execution.
Watchout for a review of the Bridge pattern in javascript in my next post

Wednesday, May 28, 2008

A Look at The Genesis of Google AdWords

Have you ever thought about how the giant search engine of today,Google inc ever come up with the idea of ads on there site that is not only enriching them but millions of others arround the world? Well in my research i have uncovered an article that showed the innovative idea behind the Google AdWord revenue generation.You could read more about here
History of Google AdWords
I hope you will find this an interesting read

Browser Detection and Cross Browser Support

Have you ever designed a site that looked great in Explorer only for it to look messed up in Firefox or Opera? Well i have and i have looked for ways of dealing with this issue.While conducting a search on the net i came a cross this article that explored the problem.
The article talked a lot about the various browsers and the methods for detecting the each
the link to this article is Browser Detecion and Cross Browser Support
I hope those of you who have the same problem as i do will find this article a great read.

Saturday, May 24, 2008

How do i pick up all the fields of a form with javascript?

I have devised a simple way of picking up all the datas in my form for either
client side validation or for packaging and sending it to the server via Ajax
I will illustrate this with a basic form with two input box and two select box
the form structure first

<form method='post' action=''>
<table width='400'align='center'>
<tbody>
<tr>
<td>Firstname</td>
<td><input type='text' id='csFname' name='ssFname'>/</td>
</tr>
<tr>
<td>Lastname</td>
<td><input type='text' id='csLname' name='ssLname'>/</td>
</tr>
<tr>
<td>Age</td>
<td><select id='csAge' name='ssAge'>
< option value=''>Select one< option >
< option value='20'>20< option >
< option value='30'>30< option >
< /select >
</td>
</tr>
<tr>
<td>Sex</td>
<td><select id='csSex' name='ssSex'>
< option value=''>Select one< option >
< option value='Male'>Male< option >
< option value='Female'>Female< option >
< /select >
</td>
</tr>
< tr > < td colspan='2'> < input type='button' value='Submit'/>
</ td > < /tr >
</tbody>
</table>
</form>
All that is needed now is to write the script that will pick up all the data
to do this i always use javascript objects method of coding
or what is called the singleton pattern

var handleForm={
errorCode:0,
dataToServer:null,
errorMessage:null,
/**
*A function to start up the function when the page loads
*/
initDoc:function()
{
if(!document.getElementById && !document.createTextNode)
{return;}
},
/**
* A validating function validates all the form entries
* Node this is a generic validator that determines
* the type of object to be validated and then calls
* the appropriate method to do the validating
*/
validate:function(vtype,data)
{
if(!vtype)
{return}
var self=handleForm;
switch(vtype)
{
case'name':
self.validateName(errorPlace,data);
break;
case'age':
self.validateAge(errorPlace,data);
break;
case'sex':
self.validateSex(errorPlace,data);
break;
}
return;
},
/**
* Define the specific validating scheme for
* all the entries in the validate function
* for instance the name entries validator
* would look like this
*/
validateName:function(errorDiv,dataValue)
{
var self=handleForm;

var exp=%^[a-zA-Z]{3,}$%;
if(!dataValue.match(exp))
{
return self.discardValue(errorDiv,'Invalid name') ;
}else
{return self.acceptValue(errorDiv);}
},
/**
* The discardValue and acceptValue function are
*Helper function that informs the user when something
*goes wrong and when some thing goes write
*/
discardValue:function(errorDiv,errorMsg)
{
var self=handleForm; //references the class itself
//get the place you display error, ususally in a div
var epanel=document.getElementById(errorDiv);
epanel.innerHTML='';

//set the errorCode to a number greater than 0, this tells your script
//stop any process when there is an error somewhere
self.errorCode=434;
epanel.innerHTML=errorMsg;
return;
},
/**
* This is fired when the is a correct value or acceptable value
* it set the errorCode back to 0 and clears the error display place
*/
acceptValue:function(errorDiv)
{
var self=handleForm;
var epanel=document.getElementById(errorDiv);
epanel.innerHTML='';
self.errorCode=0;
return;
},
/**
* We define the function that is called
* when the submit button is clicked
*note that this does the picking,validating and packaging
* of the data for serverside process
*/
getData:function()
{
//define and object array
var ddata=['csFirstname':null,
'csLastname':null,
'csAge':null,
'csSex':null
];

//get all the input object in the form
var inputs=document.getElementsByTagName('input');

//get all the select object in the form
var selects=document.getElementsByTagName('select');

//loop through all the input object validating and putting then into
// the object array ddata

var self=handleForm;

for(var i=0;i<inputs.length;i++)
{
var e=inputs[i];
if(e.type=='text' && e.value.length>0)
{
//here we determine the type of object it is so
// that we can validate it
//remove the prefix cs from the id and pass it to the validating
// function
var thetarget=e.id.substring(2,e.id.length);
self.validate(thetarget,e.value);

//break out of the loop if the is a problem
if(self.errorCode>0)
{
break;
}else
{
// add the value to the array object
ddata[e.id]=e.value;
}
}else
{//fields are empty
alert('Please fill out the form');
}
}
//that does it for all the input fields
// now for the select fields it is still the same loop but with slight difference

for(var k=0;k<selects.length;k++)
{
var d=selects[k];
if(d.selectedIndex>0)
{
//pick out each for validation
var thetarget=d.id.substring(2,d.id.length);
self.validate(thetarget,d.options[d.selectedIndex].value);
if(self.errorCode>0)
{
//a problem break;
}else
{
//add to the object array
ddata[d.id]=d.options[d.selectedIndex].value;
}
}else
{// an empty select box
alert('Please select something');
break;
}
}
if(self.errorCode>0)
{
// the was a problem stop the processing
return;
}
self.dataToServer=ddata;
var formattedData=self.encodeData();
//here goes the Ajax call to the server;
},
/**
* If all the validating went fine without errorCode going beyond 0
* We then encode all the data in the object array for Ajax transmission
* The function bellow does just that
*/
encodeData:function()
{
var self=handleForm;
var str='ajax=1';
var items=self.dataToServer;
for(var item in items)
{
str+='&'+ encodeURIComponent(item)+'='+ encodeURIComponent(items[item]);
}
return str;
}
}

How do i load select object with javascript

To load a select object with javascript we will write two simple functions called
doLoad,loadSelect passing in the select object reference and the data to be loaded
Here we assume the data is comming from an XML file from the server. let's first take
a look at the XML file before we go ahead to write the function
data.xml

<?xml version='1.0' encoding='utf-8'?>
<States>
<state stateName='Anambra' stateCode='100'/>
<state stateName='Adamawa' stateCode='101'/>
<state stateName='Bauchi' stateCode='102'/>
<state stateName='Edo' stateCode='103'/>
.
.
.
</States>

if we wanted to load this data in to a select object we first define our doLoad function

function doLoad(xmlDoc)
{

/**Here we pick up the select object we want
* to load based on the id we assigned to it
*/
var selObject=document.getElementById('SelectId');
if(!selObject)
{return;}
/**
* Next we get the state element of the XML file
* This will make docRoot an array of object we could
*loop through
*/
var docElem=xmlDoc.getElementsByTagName('state');

/**
* We call the loadSelect function to do the actual work
* Passing it the selectObject and the docElem
*/

loadSelect(selObject,docElem);
return;
}

And that ends the doLoad function, next we look at the loadSelect function


function loadSelect(targetObj,data)
{
if(!targetObj || !data)
{return;}

for(var k=0;k<data.length;k++)
{
var options=data[k];
var option=document.createElement('option');
option.value=options.getAttribute('stateCode');
option.appendChild(document.createTextNode(options.getAttribute('stateName')));
targetObj.appendChild(option);
option=null;
options=null;

}
return;
}

And that does the loading of the XML data into the select object
Note that the structure of the XMl data matters a lot when it comes to loading
the Select Object because Javascript has a number of ways of dealing with
XMl data with its DOM capability, i have used the most basic way of dealing
with XML using javascript DOM