🔩From EventEmitter to Evt
If you need to transition from EventEmitter to Evt without too much refactorying.
All events in a single bus
In EventEmitter you had a single instance for many event types. In EVT, on the other hand, the recommended approach is to have an EVT for every event type.
That said, it's possible to use EVT just like EventEmitter.
-const EventEmitter = require("events");
+import { Evt, to } from "evt";
-const eeBus = new EventEmitter();
+const evtBus = new Evt<
+ | ["connect", void]
+ | ["disconnect", { cause: "remote" | "local" } ]
+ | ["error", Error]
+>();
-eeBus.on("disconnect", ({ cause })=> /* ... */);
+evtBus.attach(to("disconnect", ({ cause })=> /* ... */);
-eeBus.emit("disconnect", { cause: "remote" });
+evtBus.post([ "disconnect", { cause: "remote" }):
-eeBus.once("error", error => /* ... */);
+evtBus.attachOnce(to("error"), error => /* ... */);
-eeBus.removeAllListeners();
+evtBus.detach();
-const count = eeBus.listenerCount("disconnect");
+const count = evtBus.getHandlers()
+ .filter(handler => handler.op === to("disconnect"))
+ .length;
-eeBus.removeAllListeners("disconnect");
+evtText.getHandlers()
+ .filter(handler => handler.op === to("disconnect"))
+ .forEach(({ detach })=> detach());
const callback = ()=> { /* ... */ };
-eeBus.removeListener("connect", callback);
+evtText.getHandlers()
+ .filter(handler => handler.callback === callback)
+ .forEach(({detach})=> detach());
In EVT you can use Ctx to detach many handlers at once. It's much more convenient than using the callback ref.
Extending/composing Evt
Inheritence (not recommended)
It is common practice to create classes that extends EventEmitter .
As a general rule of thumb, we tend to avoid inheritance in favor of composition but if you want to do it there is how.
Composition ( recommended approach )
Now we encourage favoring composition over inheritance and having one EVT instance for each events type.
Last updated