Skip to content

Instantly share code, notes, and snippets.

@jgable
Created April 25, 2012 22:27
Show Gist options
  • Save jgable/2493989 to your computer and use it in GitHub Desktop.
Save jgable/2493989 to your computer and use it in GitHub Desktop.
Minimum JS - Scoping 2
// 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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment