Reading the JavaScript Tea Leaves
Reading other people’s code is an interesting, and often under-rated pastime. Particularly in a language like Javascript, in which there are so many ways of doing things. Particularly particularly when coming from a language like Java that offers relatively little flexibility in how to get things done. As Ajax takes off in the java/enterprise programming space, there wil be plenty of folk in that position, being exposed to this weird javascript language properly for the first time.
Mike Foster’s x library for DHTML makes for interesting reading. Mike had previously developed a fairly complex cross-browser facade called ‘CBE’ (cross-browser environment) that wrapped up most things as objects. He then scrapped it and started on x, which did things in a much more javascripty way.
Here’s a small example, showing how to treat getters and setters differently in a language that allows varable argument lengths:
function xWidth(e,uW) {
if(!(e=xGetElementById(e))) return 0;
if (xNum(uW)) {
if (uW<0) uW = 0;
else uW=Math.round(uW);
}
else uW=-1;
var css=xDef(e.style);
if(css && xDef(e.offsetWidth) && xStr(e.style.width)) {
if(uW>=0) xSetCW(e, uW);
uW=e.offsetWidth;
}
else if(css && xDef(e.style.pixelWidth)) {
if(uW>=0) e.style.pixelWidth=uW;
uW=e.style.pixelWidth;
}
return uW;
}
There’s the usual shenanigans and object detection that we’ve alcome to love, but to me, the interesting thing is the usage. Say I’ve got a DOM element myDiv. I can query it’s width like this:
var w = xWidth(myDiv);
and also set the width to 240px like this:
xWidth(myDiv,240);
I can even set the width of one element equal to another:
xWidth(myDiv2,xWidth(myDiv1));
Clean, concise, and quite un-java-like. Also quite unlike the coding styles that you’d find in Sarissa or Prototype, to name but two others. Maybe I’ll have a stroll through their way of doing things soon…