# events-constructor

> Class for emitting events

Latest version **2.3.1** (published 2026-04-16) · MIT license · 0 weekly downloads

## Install

```sh
npm install events-constructor
pnpm add events-constructor
yarn add events-constructor
bun add events-constructor
```

## Health

**Score 60/100 (C)** — status: stable.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 2.3.1 |
| Published | 2026-04-16 |
| First published | 2020-01-09 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 27.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Author | Krivega Dmitriy |
| Maintainers | krivega |

## Links

- npm: https://www.npmjs.com/package/events-constructor
- Repository: https://github.com/Krivega/events-constructor
- Homepage: https://github.com/Krivega/events-constructor#readme
- Issues: https://github.com/Krivega/events-constructor/issues
- npm.io page: https://npm.io/package/events-constructor

## Recent versions

- 2.3.1 (latest) — 2026-04-16
- 2.3.0 — 2026-04-16
- 2.2.1 — 2026-03-02
- 2.2.0 — 2026-03-02
- 2.1.1 — 2025-09-24
- 2.0.0 — 2025-07-31
- 1.5.0 — 2025-07-30
- 1.4.0 — 2025-07-29
- 1.3.0 — 2024-10-31
- 1.2.4 — 2024-10-31
- 1.2.3 — 2024-05-21
- 1.2.2 — 2023-10-13
- 1.2.0 — 2022-05-17
- 1.1.4 — 2022-01-18
- 1.1.3 — 2021-04-07
- … 10 more at https://npm.io/package/events-constructor/versions

## README

# events-constructor

[![npm](https://img.shields.io/npm/v/events-constructor?style=flat-square)](https://www.npmjs.com/package/events-constructor)
![npm bundle size](https://img.shields.io/bundlephobia/minzip/events-constructor?style=flat-square)

Class for emitting events with strong TypeScript support

## Install

npm

```sh
npm install events-constructor
```

yarn

```sh
yarn add events-constructor
```

## Usage

### Basic Events

```js
import Events from 'events-constructor';

const eventNames = ['event1', 'event2'];
const events = new Events(eventNames);

events.on('event1', (data) => {
  console.log('event1 is called with data:', data);
});

events.trigger('event1', 'some data');
```

### Typed Events (TypeScript)

```ts
import { TypedEvents } from 'events-constructor';

type EventMap = {
  userLoaded: { id: string; name: string };
  logout: never;
};

const eventNames = ['userLoaded', 'logout'] as const;
const events = new TypedEvents<EventMap>(eventNames);

// TypeScript will enforce correct payload types
events.on('userLoaded', (user) => {
  console.log('User loaded:', user.id, user.name);
});

// ✅ Correct - TypeScript knows the payload type
events.trigger('userLoaded', { id: '1', name: 'John' });

// ❌ TypeScript error - wrong payload type
events.trigger('userLoaded', { wrong: true });

// ✅ Correct - logout event has no payload
events.trigger('logout');

// ❌ TypeScript error - logout doesn't accept payload
events.trigger('logout', { data: 'wrong' });
```

### Race Conditions

Handle multiple events with onRace conditions:

```js
// onceRace - triggers only once, then automatically unsubscribes
events.onceRace(['userLogin', 'userError'], (data, eventName) => {
  console.log(`First event: ${eventName}`, data);
});

// onRace - triggers every time any of the events occur, stays active
const unsubscribe = events.onRace(['userLogin', 'userError'], (data, eventName) => {
  console.log(`Event occurred: ${eventName}`, data);
});

// Manually unsubscribe when no longer needed
unsubscribe();
```

## API

### Events (Base Class)

#### events.on

Add listener to event

```js
events.on('event1', (data) => {
  console.log('event1 is called with data:', data);
});
```

#### events.once

Add a listener that will be called only once per event

```js
events.once('event1', (data) => {
  console.log('event1 is called with data:', data);
});
```

#### events.off

Remove listener from event

```js
events.off('event1', handler);
```

#### events.trigger

Trigger event with data

```js
events.trigger('event1', 'some data');
```

#### events.emit

Alias for trigger (Node.js EventEmitter compatibility)

```js
events.emit('event1', 'some data');
```

#### events.wait

Wait for an event to be triggered (returns Promise)

```js
const data = await events.wait('event1');
console.log('Event triggered with:', data);
```

#### events.onceRace

Listen for the first occurrence of any event from a list (automatically unsubscribes after first trigger)

```js
events.onceRace(['event1', 'event2'], (data, eventName) => {
  console.log(`${eventName} was triggered first with:`, data);
});
```

#### events.onRace

Listen for any occurrence of events from a list (stays active until manually unsubscribed)

```js
const unsubscribe = events.onRace(['event1', 'event2'], (data, eventName) => {
  console.log(`${eventName} was triggered with:`, data);
});

// Unsubscribe when no longer needed
unsubscribe();
```

#### events.removeEventHandlers

Remove all listeners

```js
events.removeEventHandlers();
```

#### events.offAll

Remove all listeners for specific event or all events

```js
// Remove all listeners for specific event
events.offAll('event1');

// Remove all listeners for all events
events.offAll();
```

#### events.triggers

Get all triggers

```js
events.triggers;
```

#### events.eachTriggers

Iterate through all triggers

```js
events.eachTriggers((trigger, eventName) => {
  console.log(`Trigger for ${eventName}:`, trigger);
});
```

#### events.deactivate()

Disable event handlers. The trigger method will not produce any effect.

```js
events.on('event1', (data) => {
  console.log('event1 is called with data:', data); //it's not called
});

events.deactivate();
events.trigger('event1', 'some data');
```

#### events.activate()

Enable event handlers.

```js
events.on('event1', (data) => {
  console.log('event1 is called with data:', data);
});

events.deactivate();
events.trigger('event1', 'some data'); // no effect

events.activate();
events.trigger('event1', 'some data'); // handler is called
```

#### events.hasHandlers

Check if event has any handlers

```js
if (events.hasHandlers('event1')) {
  console.log('Event has handlers');
}
```

#### events.destroy()

Destroy the events instance and clean up all handlers

```js
events.destroy();
// All handlers are removed and triggers are undefined
```

### TypedEvents (TypeScript)

TypedEvents extends the base Events class with strong TypeScript support:

#### Type Safety

```ts
type EventMap = {
  userLoaded: { id: string };
  logout: never;
  dataUpdated: { value: number };
};

const events = new TypedEvents<EventMap>(['userLoaded', 'logout', 'dataUpdated']);

// TypeScript enforces correct payload types
events.trigger('userLoaded', { id: '123' }); // ✅
events.trigger('logout'); // ✅ (no payload for 'never' type)
events.trigger('dataUpdated', { value: 42 }); // ✅

// TypeScript errors for incorrect usage
events.trigger('userLoaded', { wrong: true }); // ❌
events.trigger('logout', { data: 'wrong' }); // ❌
```

#### eachTriggersTyped

Strongly typed version of eachTriggers

```ts
events.eachTriggersTyped((trigger, eventName) => {
  // trigger is properly typed based on the event
  if (eventName === 'userLoaded') {
    trigger({ id: 'test' }); // TypeScript knows this is correct
  }
});
```

#### onRace (TypedEvents)

Strongly typed version of onRace with payload type safety

```ts
type EventMap = {
  userLoaded: { id: string; name: string };
  userError: { error: string };
  logout: never;
};

const events = new TypedEvents<EventMap>(['userLoaded', 'userError', 'logout']);

const unsubscribe = events.onRace(['userLoaded', 'userError'], (data, eventName) => {
  // TypeScript knows the exact payload type for each event
  if (eventName === 'userLoaded') {
    console.log('User loaded:', data.id, data.name); // data is { id: string; name: string }
  } else if (eventName === 'userError') {
    console.log('Error:', data.error); // data is { error: string }
  }
});

// Unsubscribe when no longer needed
unsubscribe();
```

### EventEmitterProxy (TypeScript helper)

`EventEmitterProxy` and `EventEmitterProxyBase` help you expose a `TypedEvents` API
directly on your own classes without repeating boilerplate methods.

```ts
import { TypedEvents, EventEmitterProxy } from 'events-constructor';

type EventMap = {
  loaded: { id: string };
  error: { message: string };
};

const eventNames = ['loaded', 'error'] as const;

class Loader extends EventEmitterProxy<EventMap> {
  public constructor() {
    super(new TypedEvents<EventMap>(eventNames));
  }

  public async load() {
    try {
      // ...
      this.events.trigger('loaded', { id: '123' });
    } catch (e) {
      this.events.trigger('error', { message: String(e) });
    }
  }
}

const loader = new Loader();

// All event methods are available directly on the instance:
loader.on('loaded', ({ id }) => {
  console.log('Loaded', id);
});
```

If you prefer to provide the `events` field yourself (for example when using
dependency injection), you can extend `EventEmitterProxyBase`:

```ts
import { TypedEvents, EventEmitterProxyBase } from 'events-constructor';

type EventMap = {
  success: void;
  fail: Error;
};

class Service extends EventEmitterProxyBase<EventMap> {
  protected readonly events: TypedEvents<EventMap>;

  public constructor(events: TypedEvents<EventMap>) {
    super();
    this.events = events;
  }
}
```

## Features

- **Type Safety**: Full TypeScript support with compile-time type checking
- **Event Validation**: Ensures only predefined events can be used
- **Memory Management**: Automatic cleanup of one-time listeners
- **Error Handling**: Built-in error handling with debug support
- **Promise Support**: Async/await support with `wait()` method
- **Race Conditions**: Handle multiple events with `onceRace()` and `onRace()`
- **Lifecycle Management**: Activate/deactivate events as needed
- **Performance**: Efficient event handling with Set-based listeners

## Maintainer

👤 **Krivega Dmitriy**

- Website: <https://krivega.com>
- Github: [@Krivega](https://github.com/Krivega)

## Contributing

Contributions, issues and feature requests are welcome!  
Feel free to check [issues page](https://github.com/Krivega/events-constructor/issues). You can also take a look at the [contributing guide](https://github.com/Krivega/events-constructor/blob/master/CONTRIBUTING.md).

## 📝 License

Copyright © 2025 [Krivega Dmitriy](https://github.com/Krivega).  
This project is [MIT](https://github.com/Krivega/events-constructor/blob/master/LICENSE) licensed.

---
_Source: https://npm.io/package/events-constructor · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
