Scoping Things Out
In our last post, we talked about ways to create objects in order to keep our code tidy and organized. The next concept we're going to explore is also a way to keep our code tidy and out of the way of each other; Closures and Scoping.
The Old and Busted way
The New Hotness
Here is a much more stable way to encapsulate your page logic using a "closure" technique.
Whoa. Settle down. I know, it's a little bit more complicated. Let's start with the toughest thing on the page; the self executing function we wrapped everything in.
Breaking it Down
All we are doing is creating a function and immediately executing it. The main reason we would want to wrap our code like this is to keep it out of the global scope and therefore more modular and tidy. After running this function, we've created a new page1 object and subscribed to the document.ready event with the page1.ready handler all without any artifacts in the global scope. Plus, we get a nice way to represent the logic on our page in an object oriented way.
Next, we use the handy dandy object initialization syntax we talked about in our last post to group together the functionality for page1. Also, in the setupEvents() method I show an example of how to subscribe to events on elements in a more isolated way than putting functions in html attributes.
Now Playing - Dashboard Confessional - Screaming Infidelities