Skip to content

Instantly share code, notes, and snippets.

@liammclennan
Last active February 11, 2024 22:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save liammclennan/4639397 to your computer and use it in GitHub Desktop.
Save liammclennan/4639397 to your computer and use it in GitHub Desktop.
DIY modules
(function (root) {
// declare a module and its dependencies
root.define = function define(name, dependencies, moduleFactory) {
root.amdModules = root.amdModules || {};
if (!_.isArray(dependencies) && typeof dependencies !== 'function')
throw new Error('dependencies must be an array. moduleFactory must be a function.');
root.amdModules[name] = {
'moduleFactory': moduleFactory || dependencies,
'dependencies': typeof (moduleFactory) === 'undefined' ? [] : dependencies
};
};
// build a module and its dependencies. Modules are cached.
root.require = function require(name) {
var module = root.amdModules[name],
deps = [];
if (typeof module === 'undefined') {
throw "Module " + name + " could not be found";
}
if (module.cached) return module.cached;
for (var i = 0; i < module.dependencies.length; i++) {
deps.push(require(module.dependencies[i]));
}
module.cached = module.moduleFactory.apply(this, deps);
return module.cached;
};
root.requireTest = function requireTest(name, overrides) {
var module = root.amdModules[name],
deps = [];
if (typeof module === 'undefined') {
throw "Module " + name + " could not be found";
}
for (var i = 0; i < module.dependencies.length; i++) {
if (overrides[module.dependencies[i]]) {
deps.push(overrides[module.dependencies[i]]);
} else {
deps.push(require(module.dependencies[i]));
}
}
return module.moduleFactory.apply(this, deps);
};
if (typeof exports !== 'undefined') {
exports.define = define;
exports.require = require;
}
})(window);
@NotMyself
Copy link

Is there a typo on line 23? Should the call to requireAmd be a call to req instead?

@liammclennan
Copy link
Author

It is definitely wrong. I have an updated version, which I will post soon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment