Thursday, January 12, 2012

Namespace Your Javascript

Imagine, if you will, any small non-trivial program, whether it's in an OOP, functional, or procedural language. To make this post easy to follow, think of Tic-Tac-Toe. What are you imagining? Maybe some kind of board data structure probably abstracted away in a container, some kind of game logic container, and so forth. This is good, this is the kind of separation that we ought to strive for when building a Tic-Tac-Toe application. Now think about the last web app you worked on. Think about your javascript file(s). Did they have the same kind of separation? If so, then stop reading. However, it is very likely that it did not have the proper level of separation. Did you have a single applicaton.js? Were you sending it for every single page load? Yikes! Did it make use of other libraries that you needed to send over on every page load? Double yikes! Maybe it looked something like this:


What we can see here is two very different responsibilities. One, we want to hide and show some_div depending on certain button clicks. Two, we want to sum a column as feedback for a form submit. Instead of namespacing these two concerns, we've cluttered the global namespace and gave functionality to every div with id some_div, every button with id some_button/some_other_button, and trigger a call back on every form submit. Furthermore we make event bindings in document ready. What happens when the specifications change and now afer totalling the column we must trigger extra events depending on the total? We'll just throw another function on there right? WRONG!

We're going to namespace. For this blog post we'll just work this simple example, and therefore, we will namespace simply. For more complex applications with many seperate files take a look at this namespace function. So, we refactor and now we have a namespace for each seperate concern.


Now, our global namespace contains only Visibility and ColumnReporter. We've moved our bindings out of document ready which means we can put them under test! The code looks cleaner, it's organized with a purpose. Furtheremore, we can separate the code into two files and send over each file only when necessary. Of course, there's more refactoring to be done, but we're on our way to clean javascript without a cluttered, bloated global namespace.

No comments:

Post a Comment