Created
January 11, 2010 17:08
-
-
Save nathansmith/274388 to your computer and use it in GitHub Desktop.
Init + Module Pattern JS
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
// JS Module Pattern: | |
// http://j.mp/module-pattern | |
// Redefine: $, window, document, undefined. | |
var APP = (function($, window, document, undefined) { | |
// Automatically calls all functions in APP.init | |
$(document).ready(function() { | |
APP.go(); | |
}); | |
// For use only inside APP. | |
var PRIVATE_CONSTANT_1 = 'foo'; | |
var PRIVATE_CONSTANT_2 = 'bar'; | |
// Expose contents of APP. | |
return { | |
// APP.go | |
go: function() { | |
var i, j = this.init; | |
for (i in j) { | |
// Run everything in APP.init | |
j.hasOwnProperty(i) && j[i](); | |
} | |
}, | |
// APP.init | |
init: { | |
call_automatically_one: function() { | |
// Called on page-load. | |
// Can still be called individually, via: | |
// APP.init.call_automatically_one(); | |
}, | |
call_automatically_two: function() { | |
// Called on page-load. | |
// Can still be called individually, via: | |
// APP.init.call_automatically_two(); | |
} | |
}, | |
util: { | |
call_specifically_one: function() { | |
// Must be called individually, via: | |
// APP.util.call_specifically_one(); | |
}, | |
call_specifically_two: function() { | |
// Must be called individually, via: | |
// APP.util.call_specifically_two(); | |
} | |
} | |
}; | |
// Parameters: Zepto/jQuery, window, document. | |
})(typeof Zepto === 'function' ? Zepto : jQuery, this, this.document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I honestly don't know what that sentence means. I get the words but I am not seeing the meaning. What is more clear use of globals trying to say? Is not
window
already a global?In all my years this has never happened to me. Why do we need to protect against it? I can think of hypothetical cases where it could be exploited but to be honest in the grand scheme of things does this actually happen enough that coders have to activly work around it?
(Keep in mind I'm not advocating disusing it. It is still a good pattern. I'm simply asking for more facts checks on the exploit ability and frequency of such use cases in the wild.)
Ahh, that makes really cleaver sense. In fact I'd argue that a good minifier worth its salt would wrap the code in this module pattern for you.