eventBus.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. var EventBus = {
  2. topices: {},
  3. localTopies: {},
  4. /**
  5. * 发布事件
  6. * @param {string} topic 主题
  7. * @param {object|string} value 数据
  8. */
  9. Publish: function (topic, value) {
  10. var uuid = window.uuid(8, 16)
  11. var format = typeof value === 'object' ? 'JSON' : 'STRING'
  12. var valstr = typeof value === 'object' ? JSON.stringify(value) : value
  13. localStorage.setItem('$$evt_' + topic, uuid + '_' + format + ':' + valstr)
  14. //发布本地事件
  15. var tc = this.localTopies[topic]
  16. if (!!tc) {
  17. tc.forEach((item) => {
  18. try {
  19. item.func(item.uuid, value)
  20. } catch (error) {
  21. logerr(error)
  22. }
  23. })
  24. }
  25. },
  26. /**
  27. * 订阅事件
  28. * @param {string} topic 主题
  29. * @param {function} callback 回调
  30. * @returns {string} 订阅ID
  31. */
  32. Subscribe: function (topic, callback) {
  33. var tc = this.topices[topic]
  34. if (!tc) {
  35. tc = []
  36. this.topices[topic] = tc
  37. }
  38. var uuid = window.uuid(8, 16)
  39. tc.push({ uuid, callback })
  40. //订阅本地事件
  41. tc = this.localTopies[topic]
  42. if (!tc) {
  43. tc = []
  44. this.localTopies[topic] = tc
  45. }
  46. tc.push({ uuid: callback.name, callback })
  47. return uuid
  48. },
  49. /**
  50. * 取消订阅
  51. * @param {string}} topic 主题
  52. * @param {string} id 订阅ID
  53. */
  54. UnSub: function (topic, id) {
  55. var tc = this.topices[topic]
  56. if (tc) {
  57. this.topices[topic] = tc.filter((x) => !x.uuid === id)
  58. }
  59. if (typeof id == 'function') {
  60. tc = this.localTopies[topic]
  61. if (tc) {
  62. this.localTopies[topic] = tc.filter((x) => !x.uuid === id.name)
  63. }
  64. }
  65. },
  66. /**
  67. * 清理存储
  68. */
  69. ClearStore() {
  70. localStorage.clear()
  71. },
  72. }
  73. window.addEventListener('storage', function (event) {
  74. if (event.key.indexOf('$$evt_') < 0) return
  75. var topic = event.key.split('_')[1]
  76. var tc = EventBus.topices[topic]
  77. if (tc && tc.length > 0) {
  78. var valstr = event.newValue.substr(event.newValue.indexOf(':') + 1)
  79. var flag = event.newValue.substr(0, event.newValue.indexOf(':'))
  80. var id = flag.substr(0, flag.indexOf('_'))
  81. var format = flag.substr(flag.indexOf('_') + 1)
  82. var valobj = format === 'JSON' ? JSON.parse(valstr) : valstr
  83. for (var j of tc) {
  84. try {
  85. j.callback(id, valobj)
  86. } catch {}
  87. }
  88. }
  89. })