Event System

An event system allows application components in the same process to communicate with each other by sending and listening for events. It helps modularize the code by sending messages between functions that do not know about each other directly.

The application or library opens the possibility to execute additional functions at a certain time of the execution. These additional functions register themselves as so-called event listeners.

An event can be multifaceted:

  • The application goes up or down.

  • A new user has been created or deleted.

  • An error was thrown.

  • A new HTTP request has come in.

Deepkit Framework and its libraries already offer various events to which the user can listen and react. However, any number of custom events can be created to make the application modularly extensible.

Below is an example of the low-level API of @deepkit/event. When using Deepkit framework, event listener registration is not done via EventDispatcher directly but via modules.

import { EventDispatcher, EventToken } from '@deepkit/event';

const dispatcher = new EventDispatcher();
const MyEvent = new EventToken('my-event');

dispatcher.listen(MyEvent, (event) => {
    console.log('MyEvent triggered!');
});
dispatcher.dispatch(MyEvent);

Installation

Since Deepkit’s event system is based on Runtime Types, it is necessary to have @deepkit/type already installed correctly. See Runtime Type Installation.

If this is done successfully, @deepkit/event can be installed or the Deepkit framework which already uses the library under the hood.

npm install @deekpit/event

Note that @deepkit/event for the controller API is based on TypeScript decorators and this feature must be enabled accordingly with experimentalDecorators once the controller API is used.

file: tsconfig.json

{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "es6",
    "moduleResolution": "node",
    "experimentalDecorators": true
  },
  "reflection": true
}

Once the library is installed, the API of it can be used directly.

Event Token

At the heart of the event system are the event tokens. They are objects that define the unique event ID and the event type. An event can be triggered and an event can be listened to via an event token. Conceptually, the person who triggers the event of an event token is also the owner of this event token. The event token decides accordingly which data is available at the event and whether asynchronous event listeners are allowed.

const MyEvent = new EventToken('my-event');

TODO asynchronous

Event Types

TODO

Propagation

TODO. event.stop()

Dependency Injection

TODO