unify.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. var forEach = require('es5-ext/object/for-each')
  3. , validValue = require('es5-ext/object/valid-object')
  4. , push = Array.prototype.apply, defineProperty = Object.defineProperty
  5. , create = Object.create, hasOwnProperty = Object.prototype.hasOwnProperty
  6. , d = { configurable: true, enumerable: false, writable: true };
  7. module.exports = function (e1, e2) {
  8. var data;
  9. (validValue(e1) && validValue(e2));
  10. if (!hasOwnProperty.call(e1, '__ee__')) {
  11. if (!hasOwnProperty.call(e2, '__ee__')) {
  12. d.value = create(null);
  13. defineProperty(e1, '__ee__', d);
  14. defineProperty(e2, '__ee__', d);
  15. d.value = null;
  16. return;
  17. }
  18. d.value = e2.__ee__;
  19. defineProperty(e1, '__ee__', d);
  20. d.value = null;
  21. return;
  22. }
  23. data = d.value = e1.__ee__;
  24. if (!hasOwnProperty.call(e2, '__ee__')) {
  25. defineProperty(e2, '__ee__', d);
  26. d.value = null;
  27. return;
  28. }
  29. if (data === e2.__ee__) return;
  30. forEach(e2.__ee__, function (listener, name) {
  31. if (!data[name]) {
  32. data[name] = listener;
  33. return;
  34. }
  35. if (typeof data[name] === 'object') {
  36. if (typeof listener === 'object') push.apply(data[name], listener);
  37. else data[name].push(listener);
  38. } else if (typeof listener === 'object') {
  39. listener.unshift(data[name]);
  40. data[name] = listener;
  41. } else {
  42. data[name] = [data[name], listener];
  43. }
  44. });
  45. defineProperty(e2, '__ee__', d);
  46. d.value = null;
  47. };