您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /**
  2. * @Author: Caven
  3. * @Date: 2020-01-02 15:24:38
  4. */
  5. class Event {
  6. constructor() {
  7. this._cache = {}
  8. this._registerEvent()
  9. }
  10. /**
  11. * Event registration
  12. * Subclasses need to override
  13. * @private
  14. */
  15. _registerEvent() {}
  16. /**
  17. * @param type
  18. * @param callback
  19. * @param context
  20. * @returns {any}
  21. * @private
  22. */
  23. _on(type, callback, context) {
  24. let event = this.getEvent(type)
  25. let removeCallback = undefined
  26. if (event && callback) {
  27. removeCallback = event.addEventListener(callback, context || this)
  28. }
  29. return removeCallback
  30. }
  31. /**
  32. * @param type
  33. * @param callback
  34. * @param context
  35. * @returns {boolean}
  36. * @private
  37. */
  38. _off(type, callback, context) {
  39. let event = this.getEvent(type)
  40. let removed = false
  41. if (event && callback) {
  42. removed = event.removeEventListener(callback, context || this)
  43. }
  44. return removed
  45. }
  46. /**
  47. * @param type
  48. * @param params
  49. * @private
  50. */
  51. _fire(type, params) {
  52. let event = this.getEvent(type)
  53. if (event) {
  54. event.raiseEvent(params)
  55. }
  56. }
  57. /**
  58. * Subscribe event
  59. * @param type
  60. * @param callback
  61. * @param context
  62. * @returns remove callback function
  63. */
  64. on(type, callback, context) {
  65. return this._on(type, callback, context)
  66. }
  67. /**
  68. * Subscribe once event
  69. * @param type
  70. * @param callback
  71. * @param context
  72. */
  73. once(type, callback, context) {
  74. let removeCallback = this._on(type, callback, context)
  75. removeCallback && removeCallback()
  76. }
  77. /**
  78. * Unsubscribe event
  79. * @param type
  80. * @param callback
  81. * @param context
  82. * @returns Boolean
  83. */
  84. off(type, callback, context) {
  85. return this._off(type, callback, context)
  86. }
  87. /**
  88. * Trigger subscription event
  89. * @param type
  90. * @param params
  91. */
  92. fire(type, params) {
  93. this._fire(type, params)
  94. }
  95. /**
  96. * Returns events by type
  97. * @param type
  98. * @returns Event
  99. */
  100. getEvent(type) {
  101. return this._cache[type] || undefined
  102. }
  103. }
  104. export default Event