Broadcastable
Updated on August 22, 2024Source codeTests
Broadcastable is a class that enriches application state, allowing it to:
- Broadcast itself
- Store the
BroadcastChannelinstance used for broadcasting
Construct a Broadcastable instance
The Broadcastable constructor accepts two parameters:
statePasses the state that will be made broadcastable.
state can be any type supported by the structured clone algorithm.
optionsBroadcastable instance. See the Broadcastable constructor options section for more guidance.Broadcastable constructor options
namebaleadaBroadcastChannel instance that Broadcastable uses to send messages.State and methods
stateThe state passed to the Broadcastable constructor.
If you assign a value directly to state, a setter will pass the new value to setState.
statusThe status of the Broadcastable instance.
One of 'ready', 'broadcasting', 'broadcasted', 'errored', or 'stopped'.
channelThe BroadcastChannel instance that Broadcastable uses to send messages.
errorThe error that was thrown during the last broadcast operation, when applicable.
setState(newState)Broadcastable instance's statestateBroadcastable instance (this)broadcast()Broadcastable instance's stateBroadcastable instance (this)stop()BroadcastChannel instance that Broadcastable uses to send messagesBroadcastable instance (this) Using with Listenable
Broadcastable is designed to work seamlessly with Listenable.
To listen for messages:
- Construct your
Listenableinstance, passingmessageas the event type. - Use the
toMessageListenParamsfunction exported from Baleada Logic to easily format yourBroadcastableinstance and youronMessagecallback into parameters forListenable'slistenmethod.
import {
Listenable,
Broadcastable,
toMessageListenParams,
} from '@baleada/logic'
const broadcastable = new Broadcastable('hello world'),
message = new Listenable('message')
message.listen(...toMessageListenParams(
broadcastable,
event => {
console.log(event)
}
))
Using with TypeScript
The Broadcastable constructor accepts one generic type that you can use to enforce a type for state. By default, TypeScript will infer the type from the initial state you pass to the constructor, but you can specify the type manually if needed.
const withInferredTypes = new Broadcastable(0)
withInferredTypes.state = 'a' // Type error
const withManualTypes = new Broadcastable<string | number>(0)
withManualTypes.state = 'a' // No type error
API design compliance
options object.statesetStateset<Property> methodsstatus, channel, errorbroadcast, stopstop methodable