Extending Evt

It is common practice to create classes that extends EventEmitter .

As a general rule of thumb, we tend to avoid inheritance in favor of other patterns but if you want to do it there is how.

import { Evt, to } from "evt";

class MySocket extends Evt<
    ["connect", void] |
    ["disconnect", { cause: "remote" | "local" } ] |
    ["error", Error]
    > {

    public readonly 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
        );

    }

}



const socket = new MySocket({ 
    "address": "wss://example.com"
});

(async ()=> {

  await socket.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})`)
);

Run the browser

Now we encourage favoring composition over inheritance and having one EVT instance for each events type.

Run in the browser

Last updated