🚀 DAY 5 OF LAUNCH WEEK:Introducing Webhook Events for Alert Changes.Learn more →
Socket
Book a DemoInstallSign in
Socket

@kambing86/event-bus-ts

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@kambing86/event-bus-ts

event bus for typescript and react

latest
Source
npmnpm
Version
2.0.4
Version published
Weekly downloads
5
-28.57%
Maintainers
1
Weekly downloads
 
Created
Source

event-bus

a simple event bus to be used in JavaScript/TypeScript Application, with React hook

Install

npm install @kambing86/event-bus-ts

Usage

  • add @kambing86/event-bus-ts by installing npm install @kambing86/event-bus-ts
  • create a file for event bus, for eg. "src/util/eventBus.ts"
import { createEventBus, createUseEventBus } from '@kambing86/event-bus-ts';

// string enum for Event
export enum EventType {
  ADD_TODO = 'addTodo',
  REMOVE_TODO = 'removeTodo',
}

// or just const
export const EventType = {
  ADD_TODO: 'addTodo',
  REMOVE_TODO: 'removeTodo',
} as const;

// define the payload data for Event
export type EventDataMapping = {
  [EventType.ADD_TODO]: { id: number; text: string };
  [EventType.REMOVE_TODO]: number;
};

export const eventBus = createEventBus<EventDataMapping>({ events: EventType });

export const useEventBus = createUseEventBus<EventDataMapping>(eventBus);

const subscription = eventBus.subscribe(EventType.ADD_TODO, (todo) => {
  console.log(`${todo.text} is added`);
});

// Dispatch an event with payload
eventBus.dispatch(EventType.ADD_TODO, { id: 1, text: 'Learn TypeScript' });

// or use the actions with typescript hint
eventBus.actions.addTodo({ id: 2, text: 'Learn Event Bus' });

// or use actions with the enum / const
eventBus.actions[EventType.ADD_TODO]({ id: 3, text: 'Learn React' });

// Unsubscribe from the event
setTimeout(() => {
  subscription.unsubscribe();
}, 0);
  • then use it in React component
function NewTodo() {
  // ...
  return <button onClick={() => eventBus.dispatch(EventType.ADD_TODO, newTodo)}>Add new</button>
  // or
  return <button onClick={() => eventBus.actions.addTodo(newTodo)}>Add new</button>
}

function TodoList() {
  const [todoList, setTodoList] = useState([]);

  // ...

  useEventBus(EventType.ADD_TODO, (newTodo) =>
    setTodoList((prev) => [...prev, newTodo]),
  );

  return <div>{todoList.map((todo) => <div>{todo.text}</div>)}</div>
}

Maintainers


Chua Kang Ming

Keywords

event

FAQs

Package last updated on 18 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts