選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Event.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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(
  75. type,
  76. e => {
  77. callback(e)
  78. removeCallback && removeCallback()
  79. },
  80. context
  81. )
  82. }
  83. /**
  84. * Unsubscribe event
  85. * @param type
  86. * @param callback
  87. * @param context
  88. * @returns Boolean
  89. */
  90. off(type, callback, context) {
  91. return this._off(type, callback, context)
  92. }
  93. /**
  94. * Trigger subscription event
  95. * @param type
  96. * @param params
  97. */
  98. fire(type, params) {
  99. this._fire(type, params)
  100. }
  101. /**
  102. * Returns events by type
  103. * @param type
  104. * @returns Event
  105. */
  106. getEvent(type) {
  107. return this._cache[type] || undefined
  108. }
  109. }
  110. export default Event