|
| 1 | + |
| 2 | +// This is a brain-dead simple sorta-kinda-AMD-loader. |
| 3 | +// Something like this is useful when your AngularJS app is also using RequireJS. |
| 4 | +// It doesn't implement the full AMD spec but it implements enough that 'define' should work |
| 5 | +// and then you can use loadAmdModule to synchronously execute a particular AMD module. |
| 6 | + |
| 7 | +var amdModules = {}; |
| 8 | + |
| 9 | +function define(name, deps, impl) { |
| 10 | + |
| 11 | + if (impl === undefined) { |
| 12 | + impl = deps; |
| 13 | + deps = []; |
| 14 | + } |
| 15 | + |
| 16 | + amdModules[name] = [deps, impl]; |
| 17 | + |
| 18 | +} |
| 19 | + |
| 20 | +function require() { |
| 21 | + |
| 22 | +} |
| 23 | +require.config = function () {}; |
| 24 | + |
| 25 | +function loadAmdModule(name) { |
| 26 | + |
| 27 | + var module = amdModules[name]; |
| 28 | + |
| 29 | + if (module) { |
| 30 | + if (module[2] === undefined) { |
| 31 | + var deps = module[0]; |
| 32 | + var impl = module[1]; |
| 33 | + |
| 34 | + if (! impl) { |
| 35 | + throw new Error('AMD module ' + name + ' has no implementation'); |
| 36 | + } |
| 37 | + |
| 38 | + var args = []; |
| 39 | + args.length = deps.length; |
| 40 | + for (var i = 0; i < deps.length; i++) { |
| 41 | + var depName = deps[i]; |
| 42 | + |
| 43 | + if (depName.charAt(0) === '.') { |
| 44 | + var baseParts = name.split('/'); |
| 45 | + baseParts = baseParts.slice(0, baseParts.length - 1); |
| 46 | + var depParts = baseParts.concat(depName.split('/')); |
| 47 | + for (var j = 0; j < depParts.length; j++) { |
| 48 | + var part = name[j]; |
| 49 | + if (part === '.') { |
| 50 | + name.splice(j, 1); |
| 51 | + j -= 1; |
| 52 | + } |
| 53 | + else if (part === '..') { |
| 54 | + if (j === 1 && (name[2] === '..' || name[0] === '..')) { |
| 55 | + break; |
| 56 | + } |
| 57 | + else if (j > 0) { |
| 58 | + name.splice(j - 1, 2); |
| 59 | + j -= 2; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + depName = depParts.join('/').replace('./', ''); |
| 64 | + } |
| 65 | + |
| 66 | + try { |
| 67 | + args[i] = loadAmdModule(depName); |
| 68 | + } |
| 69 | + catch (err) { |
| 70 | + // ignore errors while loading dependencies |
| 71 | + } |
| 72 | + } |
| 73 | + module[2] = impl.apply(null, args); |
| 74 | + } |
| 75 | + return module[2]; |
| 76 | + } |
| 77 | + else { |
| 78 | + throw new Error('No AMD module called ' + name); |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments