Merge pull request 'Add support for once event listeners and improve event removal' (#67) from BordedDev/snek:feat/once-event-listener into main
Reviewed-on: retoor/snek#67 Reviewed-by: retoor <retoor@noreply@molodetz.nl>
This commit is contained in:
		
						commit
						6b4709d011
					
				| @ -3,8 +3,15 @@ export class EventHandler { | |||||||
|     this.subscribers = {}; |     this.subscribers = {}; | ||||||
|   } |   } | ||||||
| 
 | 
 | ||||||
|   addEventListener(type, handler) { |   addEventListener(type, handler, { once = false } = {}) { | ||||||
|     if (!this.subscribers[type]) this.subscribers[type] = []; |     if (!this.subscribers[type]) this.subscribers[type] = []; | ||||||
|  |     if (once) { | ||||||
|  |       const originalHandler = handler; | ||||||
|  |       handler = (...args) => { | ||||||
|  |         originalHandler(...args); | ||||||
|  |         this.removeEventListener(type, handler); | ||||||
|  |       }; | ||||||
|  |     } | ||||||
|     this.subscribers[type].push(handler); |     this.subscribers[type].push(handler); | ||||||
|   } |   } | ||||||
| 
 | 
 | ||||||
| @ -12,4 +19,15 @@ export class EventHandler { | |||||||
|     if (this.subscribers[type]) |     if (this.subscribers[type]) | ||||||
|       this.subscribers[type].forEach((handler) => handler(...data)); |       this.subscribers[type].forEach((handler) => handler(...data)); | ||||||
|   } |   } | ||||||
|  | 
 | ||||||
|  |   removeEventListener(type, handler) { | ||||||
|  |     if (!this.subscribers[type]) return; | ||||||
|  |     this.subscribers[type] = this.subscribers[type].filter( | ||||||
|  |       (h) => h !== handler | ||||||
|  |     ); | ||||||
|  | 
 | ||||||
|  |     if (this.subscribers[type].length === 0) { | ||||||
|  |       delete this.subscribers[type]; | ||||||
|  |     } | ||||||
|  |   } | ||||||
| } | } | ||||||
|  | |||||||
| @ -142,10 +142,9 @@ export class Socket extends EventHandler { | |||||||
|       method, |       method, | ||||||
|       args, |       args, | ||||||
|     }; |     }; | ||||||
|     const me = this; |  | ||||||
|     return new Promise((resolve) => { |     return new Promise((resolve) => { | ||||||
|       me.addEventListener(call.callId, (data) => resolve(data)); |       this.addEventListener(call.callId, (data) => resolve(data), { once: true}); | ||||||
|       me.sendJson(call); |       this.sendJson(call); | ||||||
|     }); |     }); | ||||||
|   } |   } | ||||||
| } | } | ||||||
|  | |||||||
		Loading…
	
		Reference in New Issue
	
	Block a user