Created
January 17, 2012 07:40
-
-
Save lukehoban/1625486 to your computer and use it in GitHub Desktop.
AMD using ES6 module loaders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
// 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