JavaScript Programming Patterns
JavaScript is meant to be used to add behaviour to a website, might it be for form validation or for more complex operations like drag & drop functionality or performing asynchronous requests to the webserver (aka Ajax). During the past few years, JavaScript libraries became increasingly popular. One of the reasons is definitely that websites are getting more and more complex and reinventing the wheel each time is not acceptable if you are working on a tight schedule. But letting aside libraries and focusing on the “bare” syntax of JavaScript, it is very valuable to know what kind of options you have in terms of programming patterns when writing JavaScript.
In this article I am trying to present some of the techniques out there that I have discovered. The patterns I would like to mention are the following:
- The Old-School Way
- Singleton
- Module Pattern
- Revealing Module Pattern
- Custom Objects
- Lazy Function Definition
The way I decided to present and compare these different patterns is by solving the same given task with every pattern. The task is: You have three links on a page and when clicking the links, the background color of that link should change to a preconfigured value. The markup looks like this:
<ul> <li><a href="http://news.bbc.co.uk/">News on BBC website</a></li> <li><a href="http://nytimes.com/">Frontpage of The New York Times</a></li> <li><a href="http://www.guardian.co.uk/">Guardian Unlimited</a></li> </ul>
To complete the task given, you essentially would need to complete the following steps:
- Define the background colors in some kind of configuration variable
- Get all the anchors on the page and store them in a data structure (array)
- Loop through that array and attach an onclick event to them, pointing to a function that changes the background color
- If the link gets clicked that function gets executed and the background color of the link clicked gets changed
The Old-School Way
I would like to start off with demonstrating how this task would have been solved in the late 90′s, early 2000. At that time, JavaScript was purely used to do sequential programming, defining one function after the other. Nobody worried about namespace. Nobody worried about re-usability of code. Nobody worried in general, cause each script kiddie was paid a huge amount of money. They couldn’t be bothered with such things. To make everything at least a bit more neat, I decided to use function definitions, even if you could write some of that code straight into the bode of the page (to make things even worse). So you could have 2 functions:
- anchorChange1: collects the links and attaches the event
- changeColor1: executes the actual swap of the background color
Without further ado, your final code might look like this:
function changeColor1(linkObj, newColor) { linkObj.style.backgroundColor = newColor; } function anchorChange1() { // set configuration var config = { colors: [ "#F63", "#CC0", "#CFF" ] }; // get all links on page var anchors = document.getElementsByTagName("a"); var size = anchors.length; // loop through anchors and attach events for (var i = 0; i < size; i++) { anchors[i].color = config.colors[i]; anchors[i].onclick = function () { changeColor1(this, this.color); return false; }; } }
In a JavaScript block on the page – after the anchor and preferably close to the closing body-tag – you then only need to call the main function:
<script type="text/javascript"> anchorChange1(); </script>
Please proceed to the working example. It works fine, although it has the problem of cluttering up the global namespace. This means, in a much more complex situation with several developers working on the same project, you have a big problem if someone comes up with something like this:
function changeColor1() { alert("oh noes, my code got overwritten!"); }
Page 1 of 6 | Next page