From dd74345242ed7bc6e47d2eb8217b03f030eddab1 Mon Sep 17 00:00:00 2001 From: Ansolve Date: Mon, 27 Nov 2023 19:27:55 +0800 Subject: [PATCH] refactor: use dependency inject. --- game/src/lib/announce.js | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/game/src/lib/announce.js b/game/src/lib/announce.js index 1960aae2b..a3e8e17f6 100644 --- a/game/src/lib/announce.js +++ b/game/src/lib/announce.js @@ -12,16 +12,28 @@ export class Announce { /** * @type {EventTarget} */ - #handler; + #eventTarget; /** * @type {WeakMap} */ #records; - constructor() { - this.#handler = new EventTarget(); - this.#records = new WeakMap(); + /** + * @type {FunctionConstructor} + */ + #SubscriberType; + + /** + * + * @param {EventTarget} eventTarget + * @param {WeakMap} records + * @param {FunctionConstructor} [SubscriberType] + */ + constructor(eventTarget, records, SubscriberType = AnnounceSubscriber) { + this.#eventTarget = eventTarget; + this.#records = records; + this.#SubscriberType = SubscriberType; } /** @@ -35,7 +47,7 @@ export class Announce { * @returns {T} */ publish(name, values) { - this.#handler.dispatchEvent(new CustomEvent(name, { + this.#eventTarget.dispatchEvent(new CustomEvent(name, { detail: [values, name] })); return values; @@ -58,7 +70,7 @@ export class Announce { if (this.#records.has(method)) subscriber = this.#records.get(method); else { - subscriber = new AnnounceSubscriber(method, this.#handler); + subscriber = new this.#SubscriberType(method, this.#eventTarget); this.#records.set(method, subscriber); } subscriber.subscribe(name);