From e412109852e32ac0d2117185cb282fbb94c7a2da Mon Sep 17 00:00:00 2001 From: Jon Staab Date: Tue, 4 Feb 2025 14:16:07 -0800 Subject: [PATCH] Add handler removers to worker --- packages/lib/src/Worker.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/packages/lib/src/Worker.ts b/packages/lib/src/Worker.ts index a4c9777..e7df108 100644 --- a/packages/lib/src/Worker.ts +++ b/packages/lib/src/Worker.ts @@ -1,3 +1,5 @@ +import {remove} from "./Tools.js" + /** Symbol used to identify global handlers */ const ANY = Symbol("worker/ANY") @@ -91,6 +93,21 @@ export class Worker { this.handlers.set(k, (this.handlers.get(k) || []).concat(handler)) } + /** + * Removes a handler for messages with specific key + * @param k - Key to handle + * @param handler - Function to process matching messages + */ + removeHandler = (k: any, handler: (message: T) => void) => { + const newHandlers = remove(handler, this.handlers.get(k) || []) + + if (newHandlers.length > 0) { + this.handlers.set(k, newHandlers) + } else { + this.handlers.delete(k) + } + } + /** * Adds a handler for all messages * @param handler - Function to process all messages @@ -99,6 +116,14 @@ export class Worker { this.addHandler(ANY, handler) } + /** + * Removes a handler for all messages + * @param handler - Function to process all messages + */ + removeGlobalHandler = (handler: (message: T) => void) => { + this.removeHandler(ANY, handler) + } + /** Removes all pending messages from the queue */ clear() { this.buffer = []