broadcasterjs
A simple yet powerful pub/sub javascript event bus
Usage
No need to initialize separately. Import the 'broadcast' factory function and use to your hearts content.
START SUBSCRIPTION IN REACT
useEffect(() => {
const off = broadcast.on(['MYBROADCAST-ID', myFlagEmittedCallbackFunction])
return off
}, [myFlagEmittedCallbackFunction])
The return function is optional, BroadcasterJS is managing this anyway but React migth warn about memory leaks never the less if you don't include it.
START SUBSCRIPTION VANILLA JS
const off() = broadcast.on([
'MYBROADCAST-ID',
({ detail }) => {
document.body.append(detail + ' ')
},
])
const off() = broadcast.once([
'MYBROADCAST-ID',
({ detail }) => {
document.body.append(detail + ' ')
},
])
END SUBSCRIPTION
off()
PUBLISH IN REACT & VANILLLA JS (place anywhere)
broadcast.emit('MYBROADCAST-ID', 'Hello world')
TO VISUALLY INSPECT
Click elements tab i chrome devtools,
select event-listeners tab in second pane.
Active listeners begin with 'broadcast-' + flag name. Expand each listener to see each unique subscriber.
TO DEBUG
Add ?debug=broadcasterjs
to your url and open your devtools console.
ADVANCED
The broadcaster functions on
,once
takes an optional third value and emit
takes an optional third argument in the form of a settings object.
{
debug: boolean (false)
debugGlobal: boolean (false)
allowDoublettesSubscribers: boolean (false)
useLatestSubscriberScope?: boolean (false)
suppresDebug?: boolean (false)
}
Change log
v 1.1.0 The subscribe functions 'on' and 'once' now return a unsubscribe function (no arguments) that is much more user friendly than the previous off function. 'off' is still available but removed from the documentation.
Commands
Publish to npm: npm publish --access=public
Compile typescript: tsc
Develop: yarn start