Events

Events play an essential role in being able to develop reactive plugins that act when state changes occur in Core (block received, transaction forged, etc).

The event dispatcher implementation that ships with Core supports both synchronous and asynchronous execution of event listeners. As always, you should think carefully about when to use an event listener as they are a great way of decoupling certain aspects of your application but can end up hogging resources.

Prerequisites

Before we start, we need to inject the EventDispatcher service into our class so we can use events.

1@Container.inject(Container.Identifiers.EventDispatcherService)
2private readonly events!: Contracts.Kernel.EventDispatcher;

Registering Events & Listeners

Register a listener with the dispatcher

1this.events.listen("firstEvent", ({ name, data }) => console.log(name, data.message));

Register many listeners with the dispatcher

1this.events.listenMany([
2 ["firstEvent", listenerFunction],
3 ["secondEvent", listenerFunction]
4]);

Register a one-time listener with the dispatcher

1this.events.listenOnce("firstEvent", () => console.log("Hello World"));

Remove a listener from the dispatcher

1this.events.forget("firstEvent", listenerFunction);

Remove many listeners from the dispatcher

1this.events.forgetMany(["firstEvent", "secondEvent"]);
2 
3this.events.forgetMany([
4 ["firstEvent", listenerFunction],
5 ["secondEvent", listenerFunction]
6]);

Remove all listeners from the dispatcher

1this.events.flush();

Get all of the listeners for a given event name

1this.events.getListeners("firstEvent");

Determine if a given event has listeners

1this.events.hasListeners("firstEvent");

Dispatching Events

Fire an event and call the listeners in asynchronous order

1await this.events.dispatch("firstEvent", "Hello World");

Fire an event and call the listeners in sequential order

1await this.events.dispatchSeq("firstEvent", "Hello World");

Fire an event and call the listeners in synchronous order

1this.events.dispatchSync("firstEvent", "Hello World");

Fire many events and call the listeners in asynchronous order

1await this.events.dispatchMany([
2 ["firstEvent", "Hello World"],
3 ["secondEvent", "Hello World"]
4]);

Fire many events and call the listeners in sequential order

1await this.events.dispatchManySeq([
2 ["firstEvent", "Hello World"],
3 ["secondEvent", "Hello World"]
4]);

Fire many events and call the listeners in synchronous order

1this.events.dispatchManySync([[
2 ["firstEvent", "Hello World"],
3 ["secondEvent", "Hello World"]
4]]);
Last updated 7 months ago
Edit Page
Share:
2022 © ARK.io | All Rights Reserved
An ARK.io Product