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();
This example shows that
- The
Listen
class listens to an event calledecho
, within this handler, it sends a new event calledechoed
;if you listen to this event with the emitter, you will have notification for this event. - The
Listen
class also can handle http request to url/
, it then emitecho1
event which will invokeListen1
's listener afterListen1
pushed to the same Aex object. - The
Listen1
class listens to an event calledecho1
, within this handler, it emits a new event calledechoed1
; 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!");
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)