SEvent.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. class SEvent {
  2. constructor(eventName, isGetEvent) {
  3. if (!isGetEvent) {
  4. throw 'SEventError:get SEvent instance from SEvent.getEvent!'
  5. }
  6. this.handlers = []
  7. SEvent.events[eventName] = this
  8. }
  9. static getEvent(eventName) {
  10. SEvent.events = SEvent.events || {};
  11. const keys = Object.keys(SEvent.events)
  12. for (const key of keys) {
  13. if (key === eventName) {
  14. return SEvent.events[key]
  15. }
  16. }
  17. return new SEvent(eventName, true)
  18. }
  19. static removeEvent(eventName) {
  20. const keys = Object.keys(SEvent.events)
  21. for (const key of keys) {
  22. if (key === eventName) {
  23. SEvent.events[key].handlers = null
  24. delete SEvent.events[key]
  25. }
  26. }
  27. }
  28. static off(listenerId){
  29. for(const key of Object.keys(SEvent.events)){
  30. for(let i=0; i<SEvent.events[key].handlers.length; i++){
  31. if (listenerId === SEvent.events[key].handlers[i].id){
  32. SEvent.events[key].handlers.splice(i, 1)
  33. break
  34. }
  35. }
  36. }
  37. }
  38. on(handler) {
  39. if (handler && typeof (handler) === 'function') {
  40. this.handlers.push({
  41. id: SEvent.listenerId,
  42. handler
  43. })
  44. return SEvent.listenerId++
  45. }
  46. return 0
  47. }
  48. once(handler){
  49. const originHandler = handler
  50. handler = (args) => {
  51. originHandler(args)
  52. this.off(handler)
  53. }
  54. this.on(handler)
  55. }
  56. emit(args) {
  57. if (!(this.handlers && this.handlers.length)) return
  58. let l = this.handlers.length
  59. let i = 0
  60. while(i < this.handlers.length){
  61. this.handlers[i++].handler(...arguments)
  62. // 防止删除某些once事件的handler导致length改变
  63. if (this.handlers.length == l - 1) {
  64. i--
  65. l--
  66. }
  67. }
  68. }
  69. off(handler) {
  70. if (!(this.handlers && this.handlers.length)) return
  71. for (let i = 0; i < this.handlers.length; i++) {
  72. if (this.handlers[i].handler === handler) {
  73. this.handlers.splice(i, 1)
  74. break
  75. }
  76. }
  77. }
  78. }
  79. SEvent.listenerId = 1
  80. module.exports = SEvent