DEV Community

NotFound404
NotFound404

Posted on

Simplify your event messaging between Objects with Aex

Event Messaging decorators

Aex can route messages between objects within an Aex instance.
You only need to prefix an member function with @listen and pass a event name to it, then you are listening to the event from all aex inner http handling class now.

A simple example is like the following:

class Listen {
  private name: string;
  constructor(name?: string) {
    this.name = name || "";
  }
  @listen("echo")
  public echo(emitter: EventEmitter, ...messages: any[]) {
    emitter.emit("echoed", messages[0]);
  }

  @get("/")
  public async get(_req: any, res: any, scope: Scope) {
    scope.emitter.on("echoed1", (mesasge) => {
      res.end(mesasge + " from " + this.name);
    });
    scope.emitter.emit("echo1", "Hello");
  }
}

class Listen1 {
  @listen("echo1")
  public echo1(emitter: EventEmitter, ...messages: any[]) {
    emitter.emit("echoed1", "echoed1 " + messages[0]);
  }
}

const emitter = new EventEmitter();
const aex = new Aex(emitter);
let port: number = 0;

aex.push(Listen, "Nude");
aex.push(Listen1);
aex.prepare().start();
Enter fullscreen mode Exit fullscreen mode

This example shows that

  1. The Listen class listens to an event called echo, within this handler, it sends a new event called echoed;if you listen to this event with the emitter, you will have notification for this event.
  2. The Listen class also can handle http request to url /, it then emit echo1 event which will invoke Listen1's listener after Listen1 pushed to the same Aex object.
  3. The Listen1 class listens to an event called echo1, within this handler, it emits a new event called echoed1; if you listen to this event with the emitter, you will have notification for this event.

if we only need to send messages between objects,
just use emitter to send messages:

emitter.emit("echo", "Hello Aex!");
Enter fullscreen mode Exit fullscreen mode

emitter is an Buildin object from node.

Aex only simplifies this usage between classes, the behavior is not changed, you can refer node's EventEmitter for further information.

Event listeners of a class should not be http handlers of the class,
because they process different things.

Top comments (0)