Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,12 @@ export default defineConfig({
link: '/getting-started'
},
{
text: 'Additional Details',
link: '/additional-details'
text: 'Methods',
link: '/methods'
},
{
text: 'Broadcasting Events',
link: '/broadcasting-events'
}
]
},
Expand Down
116 changes: 0 additions & 116 deletions docs/additional-details.md

This file was deleted.

34 changes: 34 additions & 0 deletions docs/api/functions/createEmitter.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,40 @@ clear: () => void;

`void`

### count()

```ts
count: <E>() => number<E>(event, options?) => number;
```

#### Type Parameters

| Type Parameter |
| ------ |
| `E` *extends* `string` \| `number` \| `symbol` |

#### Returns

`number`

#### Type Parameters

| Type Parameter |
| ------ |
| `E` *extends* `string` \| `number` \| `symbol` |

#### Parameters

| Parameter | Type |
| ------ | ------ |
| `event` | `E` |
| `options`? | \{ `global`: `boolean`; \} |
| `options.global`? | `boolean` |

#### Returns

`number`

### emit()

```ts
Expand Down
65 changes: 65 additions & 0 deletions docs/broadcasting-events.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Broadcasting Events

Kitbag Events supports broadcasting events across multiple browser tabs/windows using the [`BroadcastChannel`](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API) API.

## Setup

Pass a channel name when creating your emitter:

```ts
import { createEmitter } from '@kitbag/events'

type Events = {
userLogin: { userId: string }
messageReceived: { content: string }
}

const emitter = createEmitter<Events>({
broadcastChannel: 'my-app-events'
})
```

## How It Works

When you specify a `broadcastChannel`:

1. **Local emission**: Events are processed by handlers in the current tab
2. **Cross-tab broadcast**: Events are automatically sent to all other tabs using the same channel name
3. **Automatic reception**: Other tabs automatically receive and process broadcasted events

## Example: Multi-tab Chat

```ts
// Tab 1: Send message
emitter.emit('messageReceived', { content: 'Hello from Tab 1!' })

// Tab 2: Automatically receives the message
emitter.on('messageReceived', ({ content }) => {
console.log('Message received:', content) // "Hello from Tab 1!"
})
```

## Channel Naming

Use descriptive, unique channel names to avoid conflicts:

```ts
// Good - specific to your app
broadcastChannel: 'my-chat-app-v1'

// Good - includes user context
broadcastChannel: `user-${userId}-events`

// Avoid - too generic
broadcastChannel: 'events'
```

## Use Cases

- **Real-time updates**: Sync user actions across tabs
- **Session management**: Notify all tabs when user logs out
- **Data synchronization**: Keep multiple tabs in sync
- **Notifications**: Broadcast system-wide alerts

## Structured Clone
Data sent is serialized using the [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
91 changes: 81 additions & 10 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Installation

Install Kitbag Events with your favorite package manager
Install Kitbag Events with your favorite package manager:

```bash
# bun
Expand All @@ -13,29 +13,100 @@ yarn add @kitbag/events
npm install @kitbag/events
```

### Create an Emitter
## Basic Usage

Create an emitter with typed events:

```ts
import { createEmitter } from '@kitbag/events'

type Events = {
hello: 'world'
userLogin: { userId: string; timestamp: number }
userLogout: { userId: string }
messageReceived: { from: string; content: string }
}

export const emitter = createEmitter<Events>()
const emitter = createEmitter<Events>()
```

## Event Handling

### Listen to specific events:

```ts
// Listen to user login events
emitter.on('userLogin', ({ userId, timestamp }) => {
console.log(`User ${userId} logged in at ${timestamp}`)
})

// Listen to message events
emitter.on('messageReceived', ({ from, content }) => {
console.log(`Message from ${from}: ${content}`)
})
```

### Global event handler (runs on all events):

```ts
emitter.on(({ kind, payload }) => {
console.log(`Event ${kind} occurred:`, payload)
})
```

### Add Listeners
### One-time event listeners:

```ts
emitter.on('hello', value => {
console.log(value)
emitter.once('userLogin', ({ userId }) => {
console.log(`First login for user ${userId}`)
})
```

### Emit Events
## Emitting Events

```ts
// Emit user login
emitter.emit('userLogin', { userId: '123', timestamp: Date.now() })

// Emit message
emitter.emit('messageReceived', { from: 'alice', content: 'Hello world!' })
```

## Waiting for Events

```ts
// Wait for next user login
const loginData = await emitter.next('userLogin')
console.log('Next login:', loginData)

// Wait for any event with timeout
const nextEvent = await emitter.next({ timeout: 5000 })
console.log('Next event:', nextEvent)
```

## Cleanup

```ts
emitter.emit('hello', 'world')
// console logs "world"
// Remove specific handler
const handler = (data: any) => console.log(data)
emitter.on('userLogin', handler)
emitter.off('userLogin', handler)

// Remove all handlers for an event
emitter.off('userLogin')

// Clear all handlers
emitter.clear()
```

## Abort Signal Support

```ts
const controller = new AbortController()

emitter.on('userLogin', ({ userId }) => {
console.log(`User ${userId} logged in`)
}, { signal: controller.signal })

// Later, abort the listener
controller.abort()
```
25 changes: 14 additions & 11 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,26 @@ layout: home
hero:
name: "Kitbag Events"
image: "/kitbag-logo.svg"
tagline: "A simple lightweight event bus written in Typescript."
tagline: "A simple lightweight event bus written in TypeScript with cross-tab broadcasting support."
actions:
- theme: brand
text: Get Started
link: /getting-started
- theme: alt
text: Additional Details
link: /additional-details
text: View API
link: /api

features:
- title: Simple
details: Tiny, zero dependencies
- title: Type safety
details: Type safe events and payload
- title: Useful API
details: Includes on, off, once, next, emit, and clear
- title: Support Global Handlers
details: Setup handlers that run on all events
---
details: Tiny, zero dependencies, easy to use
- title: Type Safe
details: Full TypeScript support with typed events and payloads
- title: Cross-Tab Support
details: Built-in broadcasting across browser tabs and windows
- title: Rich API
details: on, off, once, next, emit, count, clear, and global handlers
- title: Abort Support
details: Automatic cleanup with AbortSignal integration
- title: Promise Support
details: Async event waiting with timeout support

Loading