st-bus
v1.0.0
Published
Nano event bus library
Downloads
2
Maintainers
Readme
Nano event bus library
This is an exremely tiny, yet powerful library eventing. st-bus
makes decoupled component architecture and state mutation notification dead simple.
- ✅ Implements a socket.io-like publish/subscribe API
- ✅ Tiny:
136 byte
(best, brotli) -267 byte
(worst, umd, gz) - ✅ Zero dependencies
- ✅ First class TypeScript support
- ✅ 100% Unit Test coverage
This is how st-bus
looks like:
import { tsx, render, Ref } from 'springtype';
import { $ } from 'st-query';
import { bus } from 'st-bus';
interface ChatMessage {
user: string;
time: number;
text: string;
}
const ChatBox = () => {
const chatMessagesRef: Ref = {};
bus.on('chat:message', (event: ChatMessage) => {
$(chatMessagesRef.current).html(
<div>
{new Date(event.time)}<br />
<strong>{event.user}:</strong> {event.text}
</div>
)
});
return (
<div ref={chatMessagesRef}></div>
)
}
const TrollInput = () => {
const chatMessageInputRef: Ref = {};
const sendMessage = () => {
bus.emit('chat:message', {
user: 'foo',
time: Date.now(),
text: $(chatMessageInputRef.current).val()
})
}
return (
<div>
<input ref={chatMessageInputRef}
onKeyUp={(evt: KeyboardEvent) => (evt.keyCode === 13) ? sendMessage() : void }
type="text" />
<button onClick={sendMessage}>Send</button>
</div>
)
}
const AlterEgoChat = () => (<fragment>
<TrollBox />
<TrollInput />
</fragment>
);
render(<AlterEgoChat />);
The following contract is made between the webapp and st-router
:
export interface API {
on(topic: string, handler: EventHandler): number;
off(subscriberId: number);
emit(topic: string, event: any): void;
}
Thank you so much for supporting us financially! 🙏🏻😎🥳👍
st-bus
is brought to you by:
Please help out to make this project even better and see your name added to the list of our CONTRIBUTORS.md :tada: