Skip to main content

event

Tags CI Status Dependencies License

Strictly typed event emitter with asynciterator support.

Events should be defined as a literal object type where the key is the event name, and the value is a tuple with any amount of elements of any type.


โš ๏ธ Events must be a type, and canโ€™t be an interface due to their design differences.


type Events = {
  foo: [string];
  bar: [number, boolean];
};

class MyClass extends EventEmitter<Events> {}
const MyClassInstance = new MyClass();

function listener(num, bool) {}

// add a listener to the bar event
MyClassInstance.on("bar", listener);

// remove a listener from the bar event
MyClassInstance.off("bar", listener);

// add a one-time listener to the bar event
MyClassInstance.once("bar", (num, bool) => {});

// emit the bar event with the wanted data
MyClassInstance.emit("bar", 42, true);

// listen to all events with an async iterator
for await (const event of MyClassInstance) {
  if (event.name === "bar") {
    // event.value is of type [number, boolean]
  }
}

// listen to a specific event with an async iterator
for await (const [num, bool] of MyClassInstance.asyncOn("bar")) {
}

Maintainers

Other

Contribution

Pull request, issues and feedback are very welcome. Code style is formatted with deno fmt and commit messages are done following Conventional Commits spec.

Licence

Copyright 2020-present, the denosaurs team. All rights reserved. MIT license.