Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Created September 11, 2012 06:13
Show Gist options
  • Save ericelliott/3696394 to your computer and use it in GitHub Desktop.
Save ericelliott/3696394 to your computer and use it in GitHub Desktop.
Module Pattern for Browsers, Node, and Applitude
// Shim support for CommonJS variables. This greatly reduces logic needed.
// Note: all of these variables are supposed to be global, anyway.
var global = global || this, module = module || undefined;
(function (app) {
'use strict';
// replace the namespace string with the name of your library
var namespace = 'librarymodule',
// replace this api with your library code
api = {
foo: function () {
return 'foo';
}
};
// don't change anything from here down.
if (app.register) {
app.register(namespace, api);
} else {
namespace = app.exports ? 'exports' : namespace;
app[namespace] = api;
}
}(global.applitude || module || this));
// Later, in node:
var librarymodule = require('./lib/librarymodule');
console.log(librarymodule.foo());
// In the browser, without Applitude:
console.log(librarymodule.foo());
// With applitude, your namespace won't pollute the global scope:
console.log(applitude.librarymodule.foo());
// Or inside another module (passing in applitude)...
console.log(app.librarymodule.foo());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment