Last active
August 29, 2015 14:20
-
-
Save stacylondon/79108e292b8c23034cfa to your computer and use it in GitHub Desktop.
Refactor 2 - Add Namespace, Object Literal Notation - Commented
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ------------------------------------- | |
// my-app.js | |
// ------------------------------------- | |
// prefix with semi-colon as safety net against concatenated | |
// scripts and/or other plugins that are not closed properly | |
; | |
// check for existence of myApp in the global namespace | |
var myApp = myApp || {}; | |
// Use IIFE to: | |
// * encapsulate app logic to protect it from the global namespace | |
// * pass in namespace so can be modified locally and isn't | |
// overwritten outside of our function context | |
// * ensure $ only refers to window.jQuery (defensive programming) | |
// * $ passed through as local var rather than as globals and this | |
// (slightly) quickens the resolution process and can be more | |
// efficiently minified (especially if regularly referenced) | |
(function($, myApp) { | |
// Strict mode makes several changes to normal JavaScript semantics: | |
// * eliminates some JS silent errors by changing them to throw errors. | |
// * fixes mistakes that make it difficult for JavaScript engines to | |
// perform optimizations: strict mode code can sometimes be made to | |
// run faster than identical code that's not strict mode. Add inside | |
// the IIFE so it's defined for just the functions defined within and | |
// doesn't flip concatenating/minified code to strict inadvertently | |
'use strict'; | |
// extend the namespace with more functionality | |
$.extend(myApp, { | |
init: function() { | |
this.commonStuff(); | |
}, | |
commonStuff: function() { | |
// common code across many or all pages | |
} | |
}); | |
})(window.jQuery, window.myApp); | |
$(document).ready(function() { | |
// initialize the app when the DOM is ready | |
myApp.init(); | |
}); | |
// ------------------------------------- | |
// page-one.js | |
// ------------------------------------- | |
; | |
var myApp = myApp || {}; | |
// perform a similar existence check when defining nested children | |
myApp.pageOne = myApp.pageOne || {}; | |
(function($, myApp) { | |
'use strict'; | |
$.extend(myApp.pageOne, { | |
init: function() { | |
this.pageSpecificStuff(); | |
}, | |
pageSpecificStuff: function() { | |
// code specific to this page | |
} | |
}); | |
})(window.jQuery, window.myApp); | |
$(document).ready(function() { | |
myApp.pageOne.init(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment