Giter Club home page Giter Club logo

event's Introduction

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.

The constructor takes an optional argument which defines the maximum amount of listeners per event, which defaults to 10. If this limit is surpassed, an error is thrown.


โš ๏ธ 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);

// remove all listeners from the bar event
MyClassInstance.off("bar");

// remove all listeners from the event emitter
MyClassInstance.off();

// add a one-time listener to the bar event
MyClassInstance.once("bar", listener);

// on, once, and off are chainable
MyClassInstance.on("bar", listener).off("bar", listener);

// 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.on("bar")) {
}

// removes all listeners and closes async iterators
MyClassInstance.close("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.

event's People

Contributors

artiomtr avatar crowlkats avatar eliassjogreen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

event's Issues

Question on Internals

Hello!

I found your repo on JSR and I'm very impressed with it, especially with your use of Transform Streams. I started investigating using Transform Streams in my own work and I can't seem to get it working. Lmk if this issue should be moved somewhere else, I figured this was the best way to contact you.

Consider this test case
import { assertEquals } from "jsr:@std/assert";

class DuplexStream<T> extends TransformStream<T, T> {}

Deno.test("Streams", async (t) => {
  const stream = new DuplexStream<string>();

  const expected = [
    "Hello there",
    "Here's some string data",
    "All done",
  ];

  await t.step("Writing", async () => {
    const w = stream.writable.getWriter();

    for await (const element of expected) {
      await w.ready;
      // Error: Promise resolution is still pending but the event loop has already resolved.
      await w.write(element);
    }

    await w.ready;
    w.releaseLock();
  });

  await t.step("Reading", async () => {
    const r = stream.readable.values();

    const actual = await Array.fromAsync(r);

    assertEquals(actual, expected);
  });
});

When running deno test on the test case above, it responds with an error as soon as it hits await w.write(element);:

error: Promise resolution is still pending but the event loop has already resolved.

Refactoring to use a WritableStream only (test 2 below) or to pipe a ReadableStream through (test 3 below) solves the error, but these approaches are undesirable. What am I doing wrong here? I've tried looking for guides on Transform Streams and consulting MDN's docs on them, and nothing has been helpful. I'm curious to see how you avoided the same errors in your own repo, because it seems inevitable given you use only a TransformStream and don't use it as a pipe for any Readable Stream.

Test 2
import { assertEquals } from "jsr:@std/assert";

Deno.test("Streams 2", async (t) => {
  const collected: string[] = [];

  const stream = new WritableStream<string>({
    write(ch) {
      collected.push(ch);
    },
  });

  const expected = [
    "Hello there",
    "Here's some string data",
    "All done",
  ];

  await t.step("Writing", async () => {
    const w = stream.getWriter();

    for await (const element of expected) {
      await w.ready;
      await w.write(element);
    }

    await w.ready;
    w.releaseLock();
  });

  await t.step("Reading", () => {
    assertEquals(collected, expected);
  });
});
Test 3
import { assertEquals } from "jsr:@std/assert";

class DuplexStream<T> extends TransformStream<T, T> {}

Deno.test("Streams 3", async (t) => {
  const stream = new DuplexStream<string>();

  const expected = [
    "Hello there",
    "Here's some string data",
    "All done",
  ];

  await t.step("Writing & Reading", async () => {
    const r = ReadableStream.from(expected).pipeThrough(stream).values();

    const actual = await Array.fromAsync(r);

    assertEquals(actual, expected);
  });
});

Thanks so much for your time and for making such a high-quality library. I've starred this repo and hope to contribute to it when I can!

@denosaurs/event in JSR

I'm porting my deno.land/x module to JSR. However, while @denosaurs/event name exists, nothing exists in the package.

When does it get pushed to JSR?

mapping for denoland/dnt

Hi, I'm trying to convert my first NodeJS project to deno.

EvenEmiter is a very common NodeJS feature, and I do not know how to convert event usage to NodeJS code with dnt.

Do you know how to do that?

dnt issue

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.