Friday, June 1, 2012

The Revealing Module Pattern in JavaScript

For the most part of my career as a web developer JavaScript hasn't really been all that organized.  Generally, you dump everything you need on a page and call it good, and really for the most part it worked.  However, with the web becoming more and more ajaxy you'll see applications that will call in half a dozen pieces, each with their own special pieces of Javascript, all from one page.  Now, that alone isn't a problem, other than being kind of hard to organize, but what if ajaxy piece 1 has var toad = "wet"; and ajaxy piece 2 has var toad = "sprocket"? You can see the problem we might run into here as variables are redeclared in different pieces of our application. So what can we do? We can modularize our variables and methods. To do that we use a handy design pattern called the Revealing Module pattern. Here is how it might look: It works really well for keeping your code from conflicting with each other. For more design patterns for JS I came across this pretty useful site, Learning JavaScript Design Patterns

No comments:

Post a Comment