has.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. define(["module"], function (module) {
  2. var cache = (module.config && module.config()) || {};
  3. function resolve(resource, has, isBuild) {
  4. var tokens = resource.match(/[\?:]|[^:\?]+/g);
  5. var i = 0;
  6. var get = function (skip) {
  7. var term = tokens[i++];
  8. if (term === ":") {
  9. // empty string module name; therefore, no dependency
  10. return "";
  11. } else {
  12. // postfixed with a ? means it is a feature to branch on, the term is the name of the feature
  13. if (tokens[i++] === "?") {
  14. var hasResult = has(term);
  15. if (hasResult === undefined && isBuild) {
  16. return undefined;
  17. } else if (!skip && hasResult) {
  18. // matched the feature, get the first value from the options
  19. return get();
  20. } else {
  21. // did not match, get the second value, passing over the first
  22. get(true);
  23. return get(skip);
  24. }
  25. }
  26. // a module
  27. return term;
  28. }
  29. };
  30. return get();
  31. }
  32. var has = function (name) {
  33. var global = (function () {
  34. return this;
  35. })();
  36. return typeof cache[name] === "function" ? (cache[name] = cache[name](global)) : cache[name]; // Boolean
  37. };
  38. has.cache = cache;
  39. has.add = function (name, test, now, force) {
  40. (typeof cache[name] === "undefined" || force) && (cache[name] = test);
  41. return now && has(name);
  42. };
  43. has.normalize = function (resource, normalize) {
  44. var tokens = resource.match(/[\?:]|[^:\?]+/g);
  45. for (var i = 0; i < tokens.length; i++) {
  46. if (tokens[i] !== ":" && tokens[i] !== "?" && tokens[i + 1] !== "?") {
  47. // The module could be another plugin
  48. var parts = tokens[i].split("!");
  49. parts[0] = normalize(parts[0]);
  50. tokens[i] = parts.join("!");
  51. }
  52. }
  53. return tokens.join("");
  54. };
  55. has.load = function (resource, req, onLoad, config) {
  56. config = config || {};
  57. if (!resource || config.isBuild) {
  58. onLoad();
  59. return;
  60. }
  61. var mid = resolve(resource, has, config.isBuild);
  62. if (mid) {
  63. req([mid], onLoad);
  64. } else {
  65. onLoad();
  66. }
  67. };
  68. has.addModules = function (pluginName, resource, addModules) {
  69. var mid = resolve(resource, has, true);
  70. if (mid) {
  71. addModules([mid]);
  72. }
  73. };
  74. return has;
  75. });