@soerenuhrbach/event-dispatcher
TypeScript icon, indicating that this package has built-in type declarations

2.0.3 • Public • Published

@soerenuhrbach/event-dispatcher

A lightweight event dispatcher for TypeScript/JavaScript.

Installation

Install by npm

npm install --save @soerenuhrbach/event-dispatcher

or install with yarn

yarn add @soerenuhrbach/event-dispatcher

Modify your tsconfig.json to include the following settings

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

Add a polyfill for the Reflect API. You can use:

The Reflect polyfill import should only be added once, and before event dispatcher is used:

// main.ts
import "reflect-metadata";

// Your code here...

Usage

Creating a event

// test-event.ts
import { EventInterface } from "@soerenuhrbach/event-dispatcher";

class TestEvent implements EventInterface { }

Creating a event handler

Using the "@EventHandler()" decorator

// test-event-handler.ts
import { TestEvent } from './test-event'; 
import { EventHandler, EventHandlerInterface } from "@soerenuhrbach/event-dispatcher";

@EventHandler(TestEvent)
class TestEventHandler implements EventHandlerInterface<TestEvent> {
  public handle(event: TestEvent) {}
}

Using the "@when()" Decorator

// test-event-handler.ts
import { TestEvent } from './test-event'; 
import { EventHandlerInterface, when } from "@soerenuhrbach/event-dispatcher";

class TestEventHandler implements EventHandlerInterface<TestEvent> {
  @when(TestEvent)
  public handleTestEvent(event: TestEvent) {}
}

Register event handler

// main.ts
import { EventDispatcher } from '@soerenuhrbach/event-dispatcher';
import { TestEventHandler } from './test-event-handler';

const dispatcher = new EventDispatcher();
dispatcher.registerHandler(TestEventHandler);

Dispatching event

// main.ts
import { EventDispatcher } from '@soerenuhrbach/event-dispatcher';
import { TestEvent } from './test-event';
import { TestEventHandler } from './test-event-handler';

const dispatcher = new EventDispatcher();
dispatcher.registerHandler(TestEventHandler);
dispatcher.dispatch(new TestEvent).then(() => console.log('Event dispatched and executed'));

Using event dispatcher with your own di container

By default this package uses the di container provided by the package '@soerenuhrbach/di'. You can use your own di container by passing your container as constructor parameter.

// main.ts
import { EventDispatcher } from '@soerenuhrbach/event-dispatcher';
import { ContainerInterface } from '@soerenuhrbach/di';

const container: ContainerInterface = new CustomContainer();
const dispatcher = new EventDispatcher(container);

Readme

Keywords

none

Package Sidebar

Install

npm i @soerenuhrbach/event-dispatcher

Weekly Downloads

0

Version

2.0.3

License

MIT

Unpacked Size

59.5 kB

Total Files

66

Last publish

Collaborators

  • soerenuhrbach