Officially add the initial state argument to speaker

This commit is contained in:
Talia 2021-11-25 10:20:31 +01:00
parent d1c22234c3
commit 738d6ca493
2 changed files with 10 additions and 6 deletions

View file

@ -2,24 +2,24 @@ class Speaker {
#callbacks = new Set() #callbacks = new Set()
#immediate #immediate
#scheduled = [] #scheduled = []
#current #retain
constructor(immediate, current=[]) { constructor(immediate, ...initial) {
this.#immediate = immediate this.#immediate = immediate
this.#current = current this.#retain = initial
} }
listen(callback) { listen(callback) {
this.#callbacks.add(callback) this.#callbacks.add(callback)
return this.#current return this.#retain
} }
speak(...args) { speak(...args) {
this.#current = args
if (this.#immediate) { if (this.#immediate) {
for (let callback of this.#callbacks) { for (let callback of this.#callbacks) {
callback(...args) callback(...args)
} }
this.#retain = args
} else { } else {
if (!this.#scheduled.length) { if (!this.#scheduled.length) {
queueMicrotask(() => { queueMicrotask(() => {
@ -27,6 +27,7 @@ class Speaker {
for (let callback of this.#callbacks) { for (let callback of this.#callbacks) {
callback(...args) callback(...args)
} }
this.#retain = args
} }
this.#scheduled = [] this.#scheduled = []
}) })

View file

@ -6,7 +6,7 @@ Callbacks are scheduled as microtasks by default.
## Interface: ## Interface:
``` ```
Speaker(immediate=false) Speaker(immediate=false, ...initial)
// Creates a new speaker. // Creates a new speaker.
Speaker.listen(callback) Speaker.listen(callback)
// Registers a callback. // Registers a callback.
@ -16,6 +16,9 @@ Speaker.silence(callback)
// Removes a given callback // Removes a given callback
``` ```
The initial message is only used as the return value of `listen` before the
first call to `speak`.
## Example ## Example
A simple example: A simple example: