Slide 20
Slide 20 text
// Module pattern.
var APP = (function($, window, document, undefined) {
// For use only inside APP.
var PRIVATE_CONSTANT_1 = 'foo';
var PRIVATE_CONSTANT_2 = 'bar';
// Expose contents of APP.
return {
go: function() {
for (var i in APP.init) {
APP.init[i]();
}
},
// APP.init
init: {
call_automatically: function() {
// Called when DOM is ready.
// Can still be called individually, via:
// APP.init.call_automatically();
},
// etc.
},
// APP.misc
misc: {
call_specifically: function() {
// Must be called individually, via:
// APP.misc.call_specifically();
},
// etc.
}
};
// Alias window, document.
})(jQuery, this, this.document);
// Automatically run all functions in APP.init
jQuery(document).ready(function() {
APP.go();
});
Module Pattern
<< init example
Using a module pattern exposes
only one global variable, in this
case “APP” – with the rest of
your methods within an object.
It gives you the ability to use
private “constant” variables
inside your appʼs function scope.
Nesting functions within an “init”
object allows them to be called
automatically on DOM ready.