From cabf557569db3c9191924c7504c1446c87f6a768 Mon Sep 17 00:00:00 2001 From: DarkWiiPlayer Date: Thu, 25 Nov 2021 10:37:16 +0100 Subject: [PATCH] Split ImmediateSpeaker into separate class --- speaker.js | 62 +++++++++++++++++++++++++++++------------------------- speaker.md | 10 +++++++-- 2 files changed, 41 insertions(+), 31 deletions(-) diff --git a/speaker.js b/speaker.js index ef46326..2066689 100644 --- a/speaker.js +++ b/speaker.js @@ -1,43 +1,47 @@ -class Speaker { - #callbacks = new Set() - #immediate - #scheduled = [] - #retain +export class Speaker { + _callbacks = new Set() + _scheduled = [] + _retain - constructor(immediate, ...initial) { - this.#immediate = immediate - this.#retain = initial + constructor(...initial) { + this._retain = initial } listen(callback) { - this.#callbacks.add(callback) - return this.#retain + this._callbacks.add(callback) + return this._retain } speak(...args) { - if (this.#immediate) { - for (let callback of this.#callbacks) { - callback(...args) - } - this.#retain = args - } else { - if (!this.#scheduled.length) { - queueMicrotask(() => { - for (let args of this.#scheduled) { - for (let callback of this.#callbacks) { - callback(...args) - } - this.#retain = args + if (!this._scheduled.length) { + queueMicrotask(() => { + for (let args of this._scheduled) { + for (let callback of this._callbacks) { + callback(...args) } - this.#scheduled = [] - }) - } - this.#scheduled.push(args) + this._retain = args + } + this._scheduled = [] + }) } + this._scheduled.push(args) } - silence(callback) { - this.#callbacks.delete(callbacks) + forget(callback) { + this._callbacks.delete(callbacks) + } + + silence() { + this._callbacks.clear() + } +} + +export class ImmediateSpeaker extends Speaker { + speak(...args) { + for (let callback of this._callbacks) { + callback(...args) + } + this._retain = args } } diff --git a/speaker.md b/speaker.md index 88abdd7..76889d0 100644 --- a/speaker.md +++ b/speaker.md @@ -6,7 +6,7 @@ Callbacks are scheduled as microtasks by default. ## Interface: ``` -Speaker(immediate=false, ...initial) +Speaker(...initial) // Creates a new speaker. Speaker.listen(callback) // Registers a callback. @@ -24,7 +24,7 @@ first call to `speak`. A simple example: ```js -const speaker = new Speaker(true /* run callbacks immediately */) +const speaker = new Speaker() speaker.listen(value => console.log(value)) speaker.listen(value => console.warn(value)) @@ -64,3 +64,9 @@ defer(() => { defer(() => console.log("This message will appear last")) }) ``` + +## ImmediateSpeaker + +This class may likely be renamed in the future. + +Extends the speaker class, but doesn't defer its callbacks to a mycrotask.