Add handler removers to worker

This commit is contained in:
Jon Staab
2025-02-04 14:16:07 -08:00
parent 45d3311602
commit e412109852
+25
View File
@@ -1,3 +1,5 @@
import {remove} from "./Tools.js"
/** Symbol used to identify global handlers */ /** Symbol used to identify global handlers */
const ANY = Symbol("worker/ANY") const ANY = Symbol("worker/ANY")
@@ -91,6 +93,21 @@ export class Worker<T> {
this.handlers.set(k, (this.handlers.get(k) || []).concat(handler)) 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 * Adds a handler for all messages
* @param handler - Function to process all messages * @param handler - Function to process all messages
@@ -99,6 +116,14 @@ export class Worker<T> {
this.addHandler(ANY, handler) 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 */ /** Removes all pending messages from the queue */
clear() { clear() {
this.buffer = [] this.buffer = []