diff --git a/speaker.js b/speaker.js index 8a67e95..ef46326 100644 --- a/speaker.js +++ b/speaker.js @@ -2,24 +2,24 @@ class Speaker { #callbacks = new Set() #immediate #scheduled = [] - #current + #retain - constructor(immediate, current=[]) { + constructor(immediate, ...initial) { this.#immediate = immediate - this.#current = current + this.#retain = initial } listen(callback) { this.#callbacks.add(callback) - return this.#current + return this.#retain } speak(...args) { - this.#current = args if (this.#immediate) { for (let callback of this.#callbacks) { callback(...args) } + this.#retain = args } else { if (!this.#scheduled.length) { queueMicrotask(() => { @@ -27,6 +27,7 @@ class Speaker { for (let callback of this.#callbacks) { callback(...args) } + this.#retain = args } this.#scheduled = [] }) diff --git a/speaker.md b/speaker.md index 991a506..88abdd7 100644 --- a/speaker.md +++ b/speaker.md @@ -6,7 +6,7 @@ Callbacks are scheduled as microtasks by default. ## Interface: ``` -Speaker(immediate=false) +Speaker(immediate=false, ...initial) // Creates a new speaker. Speaker.listen(callback) // Registers a callback. @@ -16,6 +16,9 @@ Speaker.silence(callback) // Removes a given callback ``` +The initial message is only used as the return value of `listen` before the +first call to `speak`. + ## Example A simple example: