event.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // 发布订阅,事件模型
  2. var Event = (function () {
  3. var _default = 'default';
  4. var _shift = Array.prototype.shift;
  5. var _unshift = Array.prototype.unshift;
  6. function createEvent() {
  7. var namespaceCache = {}
  8. function _listen(cache, key, fn) {
  9. if (cache[key]) {
  10. cache[key].push(fn)
  11. } else {
  12. cache[key] = [fn]
  13. }
  14. }
  15. function _trigger() {
  16. var args = arguments
  17. return new Promise(function(resolve) {
  18. setTimeout(function () {
  19. var cache = _shift.call(args);
  20. var key = _shift.call(args);
  21. var stack = cache[key]
  22. if (!stack || stack.length === 0) return;
  23. stack.forEach(function (fn) {
  24. fn.apply(this, args)
  25. })
  26. resolve(stack);
  27. }, 100)
  28. })
  29. }
  30. function _remove(cache, key, fn) {
  31. var stack = cache[key]
  32. if (!stack || stack.length === 0) return
  33. if (fn) {
  34. for (var i = stack.length; i >= 0; i--) {
  35. if (stack[i] === fn) {
  36. stack.splice(i, 1)
  37. }
  38. }
  39. } else {
  40. stack.length = 0
  41. }
  42. }
  43. function _create(namespace) {
  44. namespace = namespace || _default
  45. if (namespaceCache[namespace]) {
  46. return namespaceCache[namespace]
  47. }
  48. var cache = {}
  49. var ret = {
  50. listen: function (key, fn) {
  51. _listen(cache, key, fn)
  52. },
  53. once: function (key, fn) {
  54. fn.__once = true
  55. _listen(cache, key, fn)
  56. },
  57. remove: function (key, fn) {
  58. _remove(cache, key, fn)
  59. },
  60. trigger: function () {
  61. _unshift.call(arguments, cache)
  62. _trigger.apply(this, arguments).then(function (stack) {
  63. if (stack) {
  64. for (var i = stack.length; i >= 0; i--) {
  65. if (stack[i] && stack[i].__once) {
  66. stack.splice(i, 1)
  67. }
  68. }
  69. }
  70. })
  71. }
  72. }
  73. namespaceCache[namespace] = ret;
  74. return ret
  75. }
  76. return {
  77. create: _create,
  78. once: function () {
  79. this.create().once.apply(this, arguments)
  80. },
  81. listen: function () {
  82. this.create().listen.apply(this, arguments)
  83. },
  84. remove: function () {
  85. this.create().remove.apply(this, arguments)
  86. },
  87. trigger: function () {
  88. this.create().trigger.apply(this, arguments)
  89. }
  90. }
  91. }
  92. return createEvent()
  93. })();