Quantcast
Channel: Clarity Blogs » Javascript
Viewing all articles
Browse latest Browse all 12

Bare Minimum JS – Part 2 – Scoping

$
0
0

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
function highlightMenu() {
// Find my the current menu item and highlight it...
};
 
function loadWizzyMathinger() {
// Load the almighty Wizzy Mathinger
};
 
function handleItemClick(evt) {
 
};
 
// On Document Ready
$(function() {
highlightMenu();
loadWizzyMathinger();
 
});
 
// Maybe later in the page, autoload = you do something like this
<a href="#" onclick"handleItemClick">Some Item</a>
view raw badScoping.js This Gist brought to you by GitHub.

Here’s a common story.  You start out with just a couple pages on your website.  You don’t see the harm in just throwing your javascript directly in a script block, maybe even (<gasp>) directly calling javascript from html event attributes.  But, quickly, you’ve added a bunch of new objects to the global scope and if your application ever gets much more complicated your going to end up having a hard time finding what functions are firing and debugging code paths because of the lack of structure.

First off, shame on you for putting javascript in an HTML attribute.  Somebody has to make a value judgement at some point, and for me, it’s javascript event handlers on HTML tags.  Sorry, had to be said.

The New Hotness

Here is a much more stable way to encapsulate your page logic using a “closure” technique.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
// pages.Page1.js
// I like to include the file name at the top in case we ever concatenate our scripts and need to find this file to debug.
 
// Wrap each block of code in a self executing function.
// At the bottom, we pass in these objects to this function and immediately execute it.
(function($, window, document) {
"use strict";
// Optionally, a single string "use strict" will force strict mode and help you catch common javascript errors before they get into the wild.
// Pass in jQuery and the window object to protect from other people messing with their values.
// Also, if you are referencing window or document alot, minimizers can optimize this file into a smaller size.
var page1 = {
ready: function() {
highlightMenu();
loadWizzyMathinger();
setupEvents();
},
highlightMenu: function() {
// Highlight the current menu item.
},
loadWizzyMathinger: function() {
// Load the mystical Wizzy Mathinger...
},
setupEvents: function() {
// workaround for javascript's crazy scoping of "this"
var self = this;
// A better way of handling any time .someItem is clicked on the page.
$(document).delegate("a.someItem", "click", function(evt) {
self._handleItemClick(evt);
});
},
// By convention, "private" methods usually are preceded by an underscore. It also helps to keep them out of the way when ordered (in intellisense, for example)
_handleItemClick: function(evt) {
// Handle our item click.
}
};
// On document ready hook.
$(page1.ready);
}(jQuery, window, document));

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.readyhandler 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.

The “use strict” is kind of esoteric, but it brings some helpful checks for some of the quirks of javascript.  I won’t go too much into detail here, but check out John Resig’s great article on strict mode.

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.

Next Time

Classes and scoping can really start to make your Javascript heavy projects much easier to handle.  But, it gets even better when we start to introduce another concept called the Module Export pattern.  Stay tuned, it’s gonna be good for you, I promise.

Now PlayingDashboard Confessional – Screaming Infidelities

 


Viewing all articles
Browse latest Browse all 12

Trending Articles