brikz.js 2.3 KB

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