Skip to content

Instantly share code, notes, and snippets.

@akotlov
Last active December 30, 2015 15:19
Show Gist options
  • Save akotlov/7847740 to your computer and use it in GitHub Desktop.
Save akotlov/7847740 to your computer and use it in GitHub Desktop.
JavaScript module pattern (one of the flavors)
var module = (function () {
// private variables and functions
var foo = 'bar';
// constructor
var module = function () {
};
// prototype
module.prototype = {
constructor: module,
something: function () {
}
};
// return module
return module;
})();
var my_module = new module();
// Pass global variables
var module = (function (window, document, $) {
// module stuff
})(window, document, jQuery);
// extend it with something_else();
var module = (function (module) {
module.prototype.something_else = function () {
};
return module;
})(module);
//Inject it on demand
function inject_module (module_file) {
var h = document.getElementsByTagName('head')[0];
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = module_file;
h.appendChild(s);
};
/*Tips for well-designed modules
-Don't make modules explicitly depend on each other. Everything each module needs to work should be confined into either the module or plugins that are shared among modules.
-Have modules communicate to each other through event subscriptions, not through direct calls to each other. They call this a pubsub. If you’re using jQuery, check out jQuery Tiny Pub/Sub. If not, here’s a good vanilla pubsub.
-Create a light integration layer that handles module injection and interaction.
From "http://briancray.com/posts/javascript-module-pattern. */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment