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()
#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 = []
})

View file

@ -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: