Skip to content

Class: EventBus

Defined in: src/wirestate-core/events/event-bus.ts:27

Broadcasts events to every subscriber in one container.

Remarks

Events are fire-and-forget. No handler owns the result because there is no result. Use them for "this happened" notifications.

Example

typescript
import { EventBus, createContainer } from "@wirestate/core";

const container = createContainer();
const bus = container.get(EventBus);
const unsubscribe = bus.subscribe((event) => console.log(event.type));

bus.emit("USER_LOGGED_IN", { userId: "u1" });
unsubscribe();

Constructors

Constructor

ts
new EventBus(): EventBus;

Returns

EventBus

Methods

clear()

ts
clear(): void;

Defined in: src/wirestate-core/events/event-bus.ts:132

Internal

Removes all registered handlers from the bus.

Returns

void


emit()

ts
emit<P, T, F>(
   type: T, 
   payload?: P, 
   from?: F): void;

Defined in: src/wirestate-core/events/event-bus.ts:51

Broadcasts an event to all subscribers.

Type Parameters

Type ParameterDefault typeDescription
PunknownType of the event payload.
T extends EventTypeEventTypeType of the event identifier.
FunknownType of the event source.

Parameters

ParameterTypeDescription
typeTEvent token.
payload?PEvent payload.
from?FEvent source.

Returns

void

Remarks

The bus snapshots subscribers before dispatch. A handler can unsubscribe while an event is being emitted. A thrown handler is logged and the next handler still runs.

Example

typescript
eventBus.emit("USER_LOGGED_IN", { userId: "123" }, AuthService);

has()

ts
has(): boolean;

Defined in: src/wirestate-core/events/event-bus.ts:123

Checks if the bus has any active subscribers.

Returns

boolean

true if at least one handler is registered, false otherwise.


subscribe()

ts
subscribe(handler: EventHandler): EventUnsubscriber;

Defined in: src/wirestate-core/events/event-bus.ts:90

Subscribes to every event.

Parameters

ParameterTypeDescription
handlerEventHandlerEvent handler.

Returns

EventUnsubscriber

Function that removes this subscription.

Example

typescript
const unsubscribe: EventUnsubscriber = eventBus.subscribe((event) => {
  console.log('Received event:', event);
});

unsubscribe()

ts
unsubscribe(handler: EventHandler): void;

Defined in: src/wirestate-core/events/event-bus.ts:109

Removes a previously registered event handler.

Parameters

ParameterTypeDescription
handlerEventHandlerThe handler function instance to remove.

Returns

void

Remarks

If the handler was not subscribed, this operation does nothing.