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.
In EVT you can use Ctx to detach many handlers at once. It's much more convenient than using the callback ref.
constctx=Evt.newCtx(); evtText.attach(to("connect"), ctx, ()=> { /* ... */ });evtText.attach(to("disconnect"), ctx, error => { /* ... */ });// Detach all handlers that have been attached using the ctx.ctx.done();
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.
import { Evt, to } from"evt";classMySocketextendsEvt<| ["connect",void]| ["disconnect", { cause:"remote"|"local" } ]| ["error",Error]> {publicreadonly address:string;constructor( params: { address:string; } ) {super();const { address } = params;this.address = address;setTimeout( () =>this.post(["connect",undefined]),300 );setTimeout( () =>this.post(["disconnect", { "cause":"local" }]),2000 ); }}constsocket=newMySocket({ "address":"wss://example.com"});(async ()=> {awaitsocket.waitFor(to("connect"));console.log("Socket connected");})();socket.$attach(to("error"), error => { throw error });socket.$attach( data=> data[0] ==="disconnect"? [ data[1] ] :null,//Just so you know this is what the to() operator do ({ cause })=>console.log(`socket disconnect (${cause})`));
Now we encourage favoring composition over inheritance and having one EVT instance for each events type.
import { Evt } from"evt";classMySocket {publicreadonly address:string;/* We expose a NonPostableEvt copy of the Evt and not the Evt itself so we make sure that the connect, disconnect and error events are not posted by the user of the class and only internally. */ #evtConnect =Evt.create();readonly evtConnect =Evt.asNonPostable(this.#evtConnect.pipe()); #evtDisconnect =Evt.create<{ cause:"local"|"remote" }>();readonly evtDisconnect =Evt.asNonPostable(this.#evtDisconnect.pipe()); #evtError =Evt.create<Error>();readonly evtError =Evt.asNonPostable(this.#evtError);constructor( params: { address:string; } ) {const { address } = params;this.address = address;setTimeout( () =>this.#evtConnect.post(),300 );setTimeout( () =>this.#evtDisconnect.post({ "cause":"local" }),2000 ); }}constsocket=newMySocket({ "address":"wss://example.com"});(async ()=> {awaitsocket.evtConnect.waitFor();console.log("socket connected");})();socket.evtError.attach(error => { throw error });socket.evtDisconnect.attach( ({ cause }) =>console.log(`socket disconnect (${cause})`));