st-bus

1.0.0 • Public • Published

SpringType: st-bus

Nano event bus library

Gitter

Purpose

This is an exremely tiny, yet powerful library eventing. st-bus makes decoupled component architecture and state mutation notification dead simple.

Features

  • 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

How to

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 />);

API

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;
}

Backers

Thank you so much for supporting us financially! 🙏🏻😎🥳👍

Tom

Maintainers

st-bus is brought to you by:

Aron Homberg

Contributing

Please help out to make this project even better and see your name added to the list of our CONTRIBUTORS.md 🎉

Package Sidebar

Install

npm i st-bus

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

15.5 kB

Total Files

38

Last publish

Collaborators

  • springtype-org