npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-ev

v0.4.0

Published

a typed event emitter that provides removal protection, filtering, and inheritance

Downloads

5,704

Readme


ts-ev is a typed event emitter that provides removal protection, filtering, and inheritance.

Unlike other typed event emitters, ts-ev includes a mechanism for arbitrarily deep extensions of its Emitter class:

  • Each derived class may
    • extend their parent functionality,
    • extend their parent events,
    • and define additional events.

ts-ev has zero imports, so it should be usable in any TS environment.

CHANGELOG

Features

Execution Order Guarantees:

  • Ensures that .emit() operates on the currently registered listeners.
    • In other words, listener changes during the emit loop do not effect the loop.
  • Listeners are executed in their order of addition.
    • Listeners may be prepended.
  • Matches the behavior of EventEmitter from "events".

Protection:

  • .off() will not remove the listener unless it is explicitly specified.

Filtering:

  • Supply a type assertion to narrow down the type expected by a listener.
  • Listeners are not called unless their associated filter passes.
  • Filters must be type predicates and must specify both the input and output types.
    • e.g.: (args: [number, string]): args is [1, "foo"] => args[0] === 1 && args[1] === "foo"
  • Filtering changes the listener parameters type.

Template Parameters

export class Emitter<
  BaseEvents    extends { [event: string]: (...args: any[]) => any },
  DerivedEvents extends { [event: string]: (...args: any[]) => any } = {},
> { ... }

Two template parameters are provided, one for base events and another for derived events. This is to allow for extensions of an emitter-derived class that define additional events.

For example:

// allows derived classes to define additional events (but prohibits additional "foo" events)
class Foo<DerivedEvents extends Emitter.Events.Except<"foo">>
    extends Emitter<{ foo: (data: "bar") => any }, DerivedEvents> {
  constructor() {
    this.emit("foo", "bar"); // OK
  }
}

// extend the functionality of Foo and define additional events
class Bar extends Foo<{ bar: (data: "baz") => any }> {
  constructor() {
    this.emit("foo", "bar"); // OK
    this.emit("bar", "baz"); // OK
  }
}

In this example, the Emitter BaseEvents defined by Foo are statically known to it and therefore can be used within the class and its descendants. It's DerivedEvents are not statically known by it, so they may only be used by the derived class that defines them (Bar).

public [on|prependOn|once|prependOnce]<
  Ev extends keyof BaseEvents | keyof DerivedEvents,
  Data extends EvData<BaseEvents, DerivedEvents, Ev> = EvData<BaseEvents, DerivedEvents, Ev>
> { ... }

Ev:

  • Represents the event passed to the function.

Data:

  • Represents the data received by an event listener (parameters array).
    • Set by default to the corresponding BaseEvents or DerivedEvents value.
  • Modified when a filter is provided.

Usage

import { Emitter } from "ts-ev";

// standard usage, no extensions
const emitter = new Emitter<{
  foo: (bar: "baz") => any
}>();

// emitter.emit("foo", "bar"); // TS error
emitter.emit("foo", "baz");    // OK

// extend Emitter
class Foo<
  // use a tparam to forward derived events to Emitter (allow event extensions)
  DerivedEvents extends Emitter.Events.Except<"baseEv1" | "baseEv2">
> extends Emitter<
  {
    baseEv1: (requires: number, these: string, args: boolean) => any;
    baseEv2: () => any;
  },
  DerivedEvents
> {
  constructor() {
    super();
    setTimeout(() => this.emit("baseEv1", 1, "foo", true), 100);
    setTimeout(() => this.emit("baseEv2"), 1000);

    // this.emit("derivedEv")    // ts error
    // this.emit("anythingElse") // ts error
  }
}

const foo = new Foo();

// standard on/once/off functionality

await foo.once("baseEv2");
const l = () => console.log("received");
foo.on("baseEv2", l);
foo.off("baseEv2", l);
// or foo.off("baseEv2");
// or foo.off();

// protection

foo.on("baseEv2", l, { protect: true });
foo.off("baseEv2"); // does not remove the above listener
foo.off(); // does not remove the above listener
foo.off("baseEv2", l); // OK

// filtering

foo.on(
  "baseEv1",
  // TS Types:
  //   (parameter) a: 1
  //   (parameter) b: "foo"
  //   (parameter) c: boolean
  (a, b, c) => console.log(a, b, c),
  {
    // note: must explicitly specify both the source and expected type
    filter: (data: [number, string, boolean]): data is [1, "foo", boolean] =>
      data[0] === 1 && data[1] === "foo",
  }
);

// TS Types:
//   const two: 2
//   const baz: "baz"
const [two, baz] = await foo.once("baseEv1", {
  filter: (data: [number, string, boolean]): data is [2, "bar", boolean] =>
    data[0] === 2 && data[1] === "baz",
});

// inheritance

// extending the Foo emitter
// note: this only works because Foo passes its DerivedEvents tparam to Emitter
class Bar extends Foo<{
  derivedEv: (add: "more", events: "to", the: "emitter") => any;
}> {
  constructor() {
    super();

    // can operate on base class events
    setTimeout(() => this.emit("baseEv1", 1, "foo", true), 100);
    // can operate on events provided to Foo via OtherEvents
    setTimeout(() => this.emit("derivedEv", "more", "to", "emitter"), 200);
  }
}

const bar = new Bar();
bar.on("baseEv2", () => console.log("receives base class events!"));
bar.on("derivedEv", () => console.log("receives derived class events!"));

Testing

npm test

Uses @jpcx/testts for internal unit testing.

Additionally, this project is relied on heavily by my node-kraken-api package, so it has received plenty of integration testing.

Development

Contribution is welcome! Please raise an issue or make a pull request.

Author

Justin Collier - jpcx

License

This project is licensed under the MIT License - see the LICENSE file for details