Skip to content

Instantly share code, notes, and snippets.

@rafaelcardoso
Last active January 25, 2016 18:54
Show Gist options
  • Save rafaelcardoso/681e763b7eafd10a6b6e to your computer and use it in GitHub Desktop.
Save rafaelcardoso/681e763b7eafd10a6b6e to your computer and use it in GitHub Desktop.
(function(){
var modules = {};
window.require = function(id, callback) {
var exports = modules[id];
if(!exports) {
throw new Error('o módulo '+id+' não foi definido');
} else {
callback(exports);
}
}
window.define = function(id, dependencies, callback) {
if(modules[id]){
throw new Error('o módulo '+id+' já existe');
} else {
var deps = [];
dependencies.forEach(function(dependencieName){
if(modules[dependencieName]){
deps.push(modules[dependencieName]);
} else {
throw new Error('a dependência '+dependencieName+' não foi definida');
}
});
modules[id] = callback.apply(this, deps);
}
}
})();
/// EXEMPLO
define('mars', [], function() {
return {
name : "Mars",
gravity : 0.376,
saletties : 2
}
})
define('earth', [], function() {
return {
name : "Earth",
gravity : 1,
saletties : 1
}
})
define('planets', ['mars','earth'], function(mars, earth) {
return function(){
console.log(mars.name, earth.name);
}
});
require('planets', function(planets){
planets();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment