1
0

brikz.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. define([], function () {
  2. return function Brikz(api, apiKey, initKey, backupKey) {
  3. "use strict";
  4. //jshint eqnull:true
  5. var backup = {};
  6. apiKey = apiKey || 'exports';
  7. initKey = initKey || '__init__';
  8. backupKey = backupKey || 'backup';
  9. function mixin(src, target, what) {
  10. for (var keys = Object.keys(what || src), l = keys.length, i = 0; i < l; ++i) {
  11. if (src == null) {
  12. target[keys[i]] = undefined;
  13. } else {
  14. var value = src[keys[i]];
  15. if (typeof value !== "undefined") {
  16. target[keys[i]] = value;
  17. }
  18. }
  19. }
  20. return target;
  21. }
  22. return function brikz() {
  23. Object.keys(backup).forEach(function (key) {
  24. mixin(null, api, (backup[key] || 0)[apiKey] || {});
  25. });
  26. var oapi = mixin(api, {}),
  27. order = [],
  28. chk = {};
  29. function ensure(key) {
  30. var b = brikz[key],
  31. bak = backup[key];
  32. while (typeof b === "function") {
  33. (b.deps || []).forEach(ensure);
  34. b[backupKey] = bak;
  35. mixin(null, api, api);
  36. b = new b(brikz, api);
  37. }
  38. brikz[key] = b;
  39. if (b && !chk[key]) {
  40. chk[key] = true;
  41. order.push(b);
  42. }
  43. if (b && !b[apiKey]) {
  44. b[apiKey] = mixin(api, {});
  45. }
  46. }
  47. Object.keys(brikz).forEach(ensure);
  48. mixin(oapi, mixin(null, api, api));
  49. order.forEach(function (brik) {
  50. mixin(brik[apiKey] || {}, api);
  51. });
  52. order.forEach(function (brik) {
  53. if (brik[initKey]) {
  54. brik[initKey]();
  55. if (brik[initKey].once) {
  56. delete brik[initKey];
  57. }
  58. }
  59. });
  60. backup = mixin(brikz, {});
  61. };
  62. };
  63. });