Skip to content

Instantly share code, notes, and snippets.

@lukehoban
Created January 17, 2012 07:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukehoban/1625486 to your computer and use it in GitHub Desktop.
Save lukehoban/1625486 to your computer and use it in GitHub Desktop.
AMD using ES6 module loaders
/*
// The default system module loader exposed by ES6 on the
// global object.
Object.system = {
load: function(name, callback, errback) {
// ...
},
loaded: {}
}
*/
function define(name, requirements, callback, errback) {
require(
requirements,
function(mods) {
var newMod = callback(mods);
// Store the new module into the collection
// of loaded modules for the current loader
Object.system.loaded[name] = newMod;
},
function(errs) {
errback(errs);
}
);
}
function require(requirements, callback, errback) {
var mios = {};
var errs = {};
var doneCount = 0;
function checkDone() {
if(doneCount == requirements.length) {
if(Object.keys(errs).length > 0) {
errback(new Error(errs));
}else {
var args = requirements.map(function(req) { return mios[req]; });
callback.apply(undefined, args);
}
}
}
function incrDone() { doneCount++; checkDone(); }
checkDone();
requirements.forEach(function(req) {
// Use the current loader to load the requested
// modules.
Object.system.load(
req,
function(mio) { mios[req] = mio; incrDone() },
function(err) { errs[req] = err; incrDone() }
);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment