Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bitwalker/5920670 to your computer and use it in GitHub Desktop.
Save bitwalker/5920670 to your computer and use it in GitHub Desktop.
/**
* JavaScript Module Pattern Example with "Passive Attachment"
*/
(function (root, builder, undefined) {
if (typeof define === 'function') {
// CommonJS AMD
define('MyModule', ['jQuery', 'DependencyA', 'DependencyB'], function($, a, b) {
return builder(root, $, a, b, null);
});
}
else {
// Vanilla environments (browser)
root.MyModule = builder(root, jQuery, root.DependencyA, root.DependencyB, root.MyModule);
}
})(this, function (root, $, a, b, exports, undefined) {
// MyModule is already initialized, so return it as-is
if (exports) return exports;
// Otherwise, initialize it with our module code
function MyModule() {
// Create "private" module properties
var privPropA = ...;
var privPropB = function(){...};
// Use "imported" modules
$(win.doc).ready(function(){
a();
b();
});
return this;
};
// Define public properties and functions outside of the constructor for clarity
MyModule.pubPropA = '...';
/**
* Performs foo
* @static
* @returns bar
*/
MyModule.pubFunc = function() {...};
/**
* Performs baz
* @instance
*/
MyModule.prototype.baz = function() {...};
return MyModule;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment