Thursday, June 21, 2007

objectifying javascript

The more things change, the more things stay the same. The Javascript code for the Ajax project I've worked on (the same project that motivated me to make a set of functions for mapping data onto widgets) was giving me rude flashbacks to the line-numbered BASIC days of yore. Global variables and functions are the way I've always written my Javascript (didn't everybody?). I figured it didn't matter, as long as I kept everything straight in my head, and continually looked for opportunities to replace duplicated code with functions....but then my head asplode from the criss-crossing interdependencies between all the separate bits.

Luckily, there are some pages out there that demonstrate a possible way out of the mess. Javascript Refactoring for Safer Better Ajax serves as a great guide and template for moving globally-accessible procedural code to finely-structured, encapsulated object code. Those who are a little rusty may find it helpful to first read about the syntax of Javascript custom objects at the mozilla project's developer site, or wander through Douglas Crockford's Javascript site. Structure your Javascript! recommends the less intricate approach of placing functions into nested objects to achieve namespace emulation.

The path I chose was more or less a compromise. As much as possible, I tried to identify distinct parts or organizational units in my Ajax application code. Then, for each unit, I created a singular global object containing the associated variables and functions. In effect, I broke the code up into object "modules". "Module" is a better descriptor than "object", because there still are no constructors and no real use of "this", nor is anything even remotely private (other than the few function definitions I moved inside of other functions). In other words, the code has not so much been rewritten as reorganized or relabeled. Frankly, the code's sanity may not be much improved, but mine should be.

No comments:

Post a Comment