Module Index

speaker.js

import {Speaker} from 'speaker.js'

Description

A publish/subscribe helper class that uses micro-tasks to relay messages to many subscribers.

Example

const speaker = new Speaker() speaker.listen(message => { document.title = message }) speaker.listen(message => { console.log(`Message received: ${message}`) }) speaker.speak("New page title") console.log("This line runs before any of the callbacks")

Note that the callbacks don't run immediately. They are scheduled to a micro-task to be called later on.

Methods

new Speaker(...initial) : Speaker
Constructs a new speaker. All arguments passed to the constructor will be retained and returned by any call to listen before the first time speak is called.
Speaker.listen(callback : (...args) => undefined) : [...args]
Registers a callback to be called on every new message. Returns an array containing the retained arguments of the last message.
Speaker.speak(...args)
Relays a message of zero or more arguments to all registered callbacks. As mentioned above, callbacks will not be called immediately, but scheduled in a new micro-task. The arguments are retained until speak is called again.
Speaker.forget(callback)
Removes a single callback function from its list of callbacks.
Speaker.silence()
Clears the list of callbacks completely.

Immediate Speaker

Additionally, the module exposts the ImmediateSpeaker class, which does the exact same as a normal speaker, but executes its callbacks immediately instead of scheduling a micro-task.

The API is the exact same as a normal Speaker.