Refactoring messy Javascript
February 20th, 2007
If you’re like me then you know Ruby a lot better than you know Javascript. Here’s a tidbit for refactoring your ugly javascript that I just stumbled onto.
Just now I found myself writing some javascript that looked like this:
window.onload = function() {
settings = {...snipped...}
var divObj = $('content');
var cornersObj = new curvyCorners(settings, divObj);
cornersObj.applyCornersToAll();
hideAllContent;
showContent(1);
animateStep(3, 400);
animateArrow(3, 400);
animateText(3, 800)
animateStep(2, 800);
animateArrow(2, 800);
animateText(2, 1200)
animateStep(1, 1200);
animateArrow(1, 1200);
animateText(2, 1600)
}
This is fine and dandy and works well, but it’s ugly. I realized that if this was ruby code, it was in bad need of refactoring. But how to refactor in javascript?
One important thing to understand about javascript is every object is a essentially a hash. The values of that hash can be executable functions. This makes it very easy to create namespaces for related functions.
So lets create a namespace for things that get triggered on page load.
var BootUp = {
roundCorners: function() {
settings = { ...snipped... }
var divObj = $('content');
var cornersObj = new curvyCorners(settings, divObj);
cornersObj.applyCornersToAll();
};
};
Now let’s create an object for handling showing and hiding of content pieces:
var Content = {
showDefault: function() {
Content.hideAll();
Content.show(1);
},
hideAll: function() {
[1, 2, 3, 4].each(function(n) {
$('content_' + n).hide();
}
},
show: function(n) {
$('content_' + n).show();
}
};
And lastly an object to handle animation of our 3 steps:
var Animate = {
start: function() {
Animate.group(3, 400);
Animate.group(2, 800);
Animate.group(1, 1200);
},
group: function(n, delay) {
Animate.step(n, delay);
Animate.arrow(n, delay);
Animate.text(n, delay + 400);
},
step: function(n, delay) {
setTimeout("new Effect.Appear('step_" + n + ")", delay);
},
arrow: function(n, delay) {
setTimeout("new Effect.BlindDown('step_" + n + ")", delay);
},
text: function(n, delay) { ... }
}
And now that we have all these happily name-spaced objects created, the last step is to actually use them. Simply hook a call to some of your objects functions in the window.onload event.
window.onload = function() {
BootUp.roundCorners();
Content.showDefault();
Animate.start();
}
It’s cleaner, and relatively obvious what each function do by their names and how they are grouped together.
Leave a Reply