Skip to content

Latest commit

 

History

History
156 lines (125 loc) · 3.63 KB

README.md

File metadata and controls

156 lines (125 loc) · 3.63 KB

SpringType: st-bus

Nano event bus library

Gitter

Purpose

This is an exremely tiny, yet powerful eventing library. st-bus makes it easy to decouple components. If one component wants to tell another component that something happend, emit is called. In another component, on is called to listen for such events.

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 is used:

import { tsx, render, Ref } from 'springtype';
import { $ } from 'st-query';
import { bus } from 'st-bus';

interface ChatMessage {
  user: string;
  time: number;
  text: string;
}

const TrollBox = () => {
  const chatMessagesRef: Ref = {};

  // local messages state
  const msgs = [];

  bus.on('chat:message', (event: ChatMessage) => {
    // add message to local state
    msgs.push(
      <div>
        <hr />
        {new Date(event.time).toUTCString()}
        <br />
        <strong>{event.user}: </strong>
        {event.text}
      </div>,
    );

    // re-render all messages
    $(chatMessagesRef.current).html(<div>{msgs}</div>);
  });

  return (
    <div>
      <h3>Chat room:</h3>
      <div ref={chatMessagesRef} />
    </div>
  );
};

const TrollInput = () => {
  const chatMessageInputRef: Ref = {};

  const sendMessage = () => {
    bus.emit('chat:message', {
      user: 'Anonymous',
      time: Date.now(),
      text: $(chatMessageInputRef.current).val(),
    });
    // reset input
    $(chatMessageInputRef.current).val('');
  };

  return (
    <div style={{ borderTop: '2px solid #ccc', backgroundColor: '#eee', padding: 10, marginTop: 10 }}>
      <input
        ref={chatMessageInputRef}
        placeholder="Your message..."
        onKeyUp={(evt: KeyboardEvent) => {
          if (evt.keyCode === 13) {
            sendMessage();
          }
        }}
        type="text"
      />
      <button type="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-bus:

export interface API {
  subscribers: Array<Subscriber | undefined>;
  on(topic: string, handler: EventHandler): number;
  off(subscriberId: number): void;
  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 🎉