2021-09-13 18:12:45 +00:00
|
|
|
# Speaker
|
|
|
|
|
|
|
|
A simple messaging helper that lets you publish and subscribe to messages.
|
|
|
|
Callbacks are scheduled as microtasks by default.
|
|
|
|
|
|
|
|
## Interface:
|
|
|
|
|
|
|
|
```
|
2021-11-25 09:37:16 +00:00
|
|
|
Speaker(...initial)
|
2021-09-13 18:12:45 +00:00
|
|
|
// Creates a new speaker.
|
|
|
|
Speaker.listen(callback)
|
|
|
|
// Registers a callback.
|
|
|
|
Speaker.speak(...args)
|
|
|
|
// Runs all callbacks with given arguments
|
|
|
|
Speaker.silence(callback)
|
|
|
|
// Removes a given callback
|
|
|
|
```
|
2021-10-19 16:29:07 +00:00
|
|
|
|
2021-11-25 09:20:31 +00:00
|
|
|
The initial message is only used as the return value of `listen` before the
|
|
|
|
first call to `speak`.
|
|
|
|
|
2021-10-19 16:29:07 +00:00
|
|
|
## Example
|
|
|
|
|
|
|
|
A simple example:
|
|
|
|
|
|
|
|
```js
|
2021-11-25 09:37:16 +00:00
|
|
|
const speaker = new Speaker()
|
2021-10-19 16:29:07 +00:00
|
|
|
|
|
|
|
speaker.listen(value => console.log(value))
|
|
|
|
speaker.listen(value => console.warn(value))
|
|
|
|
|
|
|
|
speaker.speak("This will be logged twice")
|
|
|
|
|
|
|
|
console.log("This message will appear last")
|
|
|
|
```
|
|
|
|
|
|
|
|
A slightly more convoluted example:
|
|
|
|
|
|
|
|
```js
|
|
|
|
import Speaker from '/speaker.js'
|
|
|
|
|
|
|
|
// A new message that schedules messages as microtasks
|
|
|
|
const speaker = new Speaker()
|
|
|
|
|
|
|
|
// A callback that calls messages as functions
|
|
|
|
speaker.listen(fn => fn())
|
|
|
|
|
|
|
|
// A shorthand wrapper around the speaker
|
|
|
|
const defer = fn => speaker.speak(fn)
|
|
|
|
|
|
|
|
// Defer a function to be called in a microtask
|
|
|
|
defer(() => console.log("This message will appear second"))
|
|
|
|
|
|
|
|
console.log("This message will appear first")
|
|
|
|
|
|
|
|
// Defer another function to be called in a microtask
|
|
|
|
defer(() => console.log("This message will appear third"))
|
|
|
|
// Note: A single speaker will use a single microtask even
|
|
|
|
// for multiple messages.
|
|
|
|
|
|
|
|
defer(() => {
|
|
|
|
// You can continue pushing messages inside the callback;
|
|
|
|
// they will be processed within the same microtask.
|
|
|
|
defer(() => console.log("This message will appear last"))
|
|
|
|
})
|
|
|
|
```
|
2021-11-25 09:37:16 +00:00
|
|
|
|
|
|
|
## ImmediateSpeaker
|
|
|
|
|
|
|
|
This class may likely be renamed in the future.
|
|
|
|
|
|
|
|
Extends the speaker class, but doesn't defer its callbacks to a mycrotask.
|