Nav apraksta

EventTarget.js 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2016 wkh237@github. All rights reserved.
  2. // Use of this source code is governed by a MIT-style license that can be
  3. // found in the LICENSE file.
  4. import Log from '../utils/log.js'
  5. const log = new Log('EventTarget')
  6. log.disable()
  7. export default class EventTarget {
  8. listeners : any;
  9. constructor() {
  10. log.info('constructor called')
  11. this.listeners = {}
  12. }
  13. /**
  14. * Add an event listener to given event type
  15. * @param {string} type Event type string
  16. * @param {(Event) => void} cb Event handler function
  17. */
  18. addEventListener(type:string, cb : () => void) {
  19. log.info('add event listener', type, cb)
  20. if(!(type in this.listeners)) {
  21. this.listeners[type] = []
  22. }
  23. this.listeners[type].push(cb)
  24. }
  25. /**
  26. * Remove an event listener
  27. * @param {string} type Type of the event listener
  28. * @param {()=>void} cb Event listener function.
  29. * @return {[type]} [description]
  30. */
  31. removeEventListener(type:string, cb:() => void) {
  32. log.info('remove event listener', type, cb)
  33. if(!(type in this.listeners))
  34. return
  35. let handlers = this.listeners[type]
  36. for(let i in handlers) {
  37. if(cb === handlers[i]) {
  38. handlers.splice(i,1)
  39. return this.removeEventListener(type, cb)
  40. }
  41. }
  42. }
  43. /**
  44. * Dispatch an event
  45. * @param {string} type Event type.
  46. * @param {Event} event Event data payload.
  47. */
  48. dispatchEvent(type:string,event:Event) {
  49. log.info('dispatch event', event)
  50. if(!(type in this.listeners))
  51. return
  52. let handlers = this.listeners[type]
  53. for(let i in handlers) {
  54. handlers[i].call(this, event)
  55. }
  56. }
  57. /**
  58. * Remove all registered listeners from this object.
  59. * @nonstandard
  60. * @return {[type]} [description]
  61. */
  62. clearEventListeners() {
  63. for(let i in this.listeners) {
  64. delete this.listeners[i]
  65. }
  66. }
  67. }