npm package: @n7e/event
Description: A lightweight library supporting event driven architecture.
Author: Martin Pettersson
Latest version: 0.2.4

# Event

A lightweight library supporting event driven architecture.

For further insights, read on.

- [Installation](#installation)
- [Events](#events)
- [Event Dispatcher](#event-dispatcher)
- [Listening For Events](#listening-for-events)
- [Stop Listening For Events](#stop-listening-for-events)
- [Dispatching Events](#dispatching-events)
- [Stopping Event Propagation](#stopping-event-propagation)
- [Default Event Dispatcher](#default-event-dispatcher)


## Installation

To install this library use your favorite package manager. No additional
steps are required to start using the library.

```shell
npm install @n7e/event
```

*This library is implemented in TypeScript but can be used with JavaScript
without any additional steps.*


## Events

Events carry with them an arbitrary payload and will by default be propagated to
all registered listeners. Propagation can however be stopped by calling
`stopPropagation()` on an event instance and no further listeners will be
invoked with that event.

All events implement the `Event` interface. To reference it simply import it and
use it as a type.

```typescript
import type { Event } from "@n7e/event";

function handle(event: Event): void {
    // ...
}
```

The `Event` interface is generic, so you can specify the payload type.

```typescript
function handle(event: Event<Array<string>>): void {
    // Okay, since the payload type is specified.
    console.log(event.payload.join(", "));
}
```


### Default Event

For convenience there's a default event implementation allowing you to supply an
arbitrary payload of any type. To use it simply import it and create a new
instance with the desired payload.

```typescript
import { DefaultEvent } from "@n7e/event";

const event = new DefaultEvent("payload");
```

*Prefer using [custom events](#custom-events) over the provided default event.*


### Custom Events

While there is a default event you can use it's recommended to create custom
payload specific events. This makes it possible for event handlers to verify
that they are able to handle the event, since type information is not available
at runtime.

Suppose we've created a user related event:

```typescript
import type { Event } from "@n7e/event";

class UserEvent implements Event<User> {
    // ...
}
```

At runtime an event handler can verify that the received event is a user related
event:

```typescript
if (!(event instanceof UserEvent)) {
    return;
}

// ...
```

Though there are no guarantees as long as you only pass valid user instances to
user related events you can safely assume that the payload of a user related
event is a user instance.


#### Stoppable Event

When implementing custom events and the default behaviour for event propagation
is desired, there's a convenient `StoppableEvent` abstract class to extend.

```typescript
import { StoppableEvent } from "@n7e/event";

class UserEvent extends StoppableEvent<User> {
    public readonly payload: User;
    
    public constructor(user: User) {
        super();
        
        this.payload = user;
    }
}
```

This lets you focus on aspects of the implementation other than the propagation.


## Event Dispatcher

An event dispatcher has the ability to dispatch events to registered listeners.
Events are dispatched with an associated identifier and passed to all event
handlers registered to that event identifier.

*`EventDispatcher` is just an interface describing the functionality of an
event dispatcher. To create an event dispatcher instance you need to reference
a specific [implementation](#default-event-dispatcher).*


## Listening For Events

To receive events an event handler needs to be registered with an event
identifier. The event identifier determines which events to receive.


### Event Handler Function

Event handlers can simple callback functions.

```typescript
eventDispatcher.addListener("test", event => console.log(event.payload));
```

If you need the event identifier it's passed as the second parameter to the
event handler function.

```typescript
eventDispatcher.addListener(
    "test",
    (event, identifier) => console.log(identifier, event.payload)
);
```


### Event Handler Class

For more advanced scenarios you can supply a class instance implementing the
`EventListener` interface.

```typescript
import type { Event, EventListener } from "@n7e/event";

class LogPayload implements EventListener {
    public handle(event: Event, identifier: string): void {
        console.log(identifier, event.payload);
    }
}

eventDispatcher.addListener("test", new LogPayload());
```


## Stop Listening For Events

To remove a registered event listener you can pass the instance to
`removeListener` along with the event identifier it was registered to. If the
event identifier is omitted the event handler will be removed from all event
identifiers it's registered to.


### Event Handler Class

If you've registered an event handler instance you can simply keep a reference
to it and pass it to `removeListener` when you don't want to receive any more
events.

```typescript
const listener = new LogPayload();

eventDispatcher.addListener("test", listener);

// The listener will no longer receive any "test" events.
eventDispatcher.removeListener(listener, "test");
```


### Event Handler Function

If you've registered an event handler function an event handler instance is
returned from `addListener`. You can use this reference to remove the event
handler function just as if it was an event handler instance.

```typescript
const listener = eventDispatcher.addListener(
    "test",
    event => console.log(event.payload)
);

// The listener will no longer receive any "test" events.
eventDispatcher.removeListener(listener, "test");
```


## Dispatching Events

To dispatch an event choose an appropriate event identifier and create a new
event instance. While custom events are preferred a default event is available
for convenience.

```typescript
import { DefaultEvent } from "@n7e/event";

eventDispatcher.dispatch("test", new DefaultEvent("payload"));
```

Event listeners registered to the "test" event identifier will receive the event
instance as long as the event propagation is not explicitly stopped.

*Prefer using [custom events](#custom-events) over the provided default event.*

Although all registered event listeners will process the event regardless, you
can wait for them by awaiting the dispatch call.

```typescript
await eventDispatcher.dispatch("test", event);
```


## Stopping Event Propagation

To prevent an event to further propagate to any registered listeners events can
be stopped.

```typescript
eventDispatcher.addListener(
    "test",
    event => {
        event.stopPropagation();
    }
);
```

After this handler has been called no further event handlers will be invoked
with this event.


## Default Event Dispatcher

There's a provided complete in-memory implementation of `EventDispatcher` that
can be used for most scenarios. To use it simply import it and create a new
event dispatcher instance.

```typescript
import { DefaultEventDispatcher } from "@n7e/event";

const eventDispatcher = new DefaultEventDispatcher();
```