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

rettime

v0.2.0

Published

Type-safe dependency-free EventTarget-inspired event emitter for browser and Node.js

Downloads

437

Readme

Rettime

Type-safe dependency-free EventTarget-inspired event emitter for browser and Node.js.

Features

  • 🎯 Event-based. Control event flow: prevent defaults, stop propagation, cancel events. Something your common Emitter can't do.
  • 🗼 Emitter-inspired. Emit event types and data, don't bother with creating Event instances. A bit less verbosity than a common EventTarget.
  • ⛑️ Type-safe. Describe the exact event types and payloads accepted by the emitter. Never emit or listen to unknown events.
  • 🧰 Convenience methods like .emitAsPromise() and .emitAsGenerator() to build more complex event-driven systems.
  • 🐙 Tiny. 700B gzipped.

[!WARNING] This library does not have performance as the end goal. In fact, since it operates on events and supports event cancellation, it will likely be slower than other emitters out there.

Motivation

Why not just EventTarget?

The EventTarget API is fantastic. It works in the browser and in Node.js, dispatches actual events, supports cancellation, etc. At the same time, it has a number of flaws that prevent me from using it for anything serious:

  • Complete lack of type safety. The type in new Event(type) is not a type argument in lib.dom.ts. It's always string. It means it's impossible to narrow it down to a literal string type to achieve type safety.
  • No concept of .prependListener(). There is no way to add a listener to run first, before other existing listeners.
  • No concept of .removeAllListeners(). You have to remove each individual listener by hand. Good if you own the listeners, not so good if you don't.
  • No concept of .listenerCount() or knowing if a dispatched event had any listeners (the boolean returned from .dispatch() indicates if the event has been prevented, not whether it had any listeners).
  • (Opinionated) Verbose. I prefer .on() over .addEventListener(). I prefer passing data than constructing new MessageEvent() all the time.

Why not just Emitter (in Node.js)?

The Emitter API in Node.js is great as well. But...

  • Node.js-specific. Emitter does not work in the browser.
  • Complete lack of type safety.
  • No concept of event cancellation. Events emit to all listeners, and there's nothing you can do about it.

Install

npm install rettime

API

.on(type, listener)

Adds an event listener for the given event type.

const emitter = new Emitter<{ hello: [string] }>()

emitter.on('hello', 'John') // ✅
emitter.on('hello', 123) // ❌ number is not assignable to type string
emitter.on('hello') // ❌ missing data argument of type string

.once(type, listener)

Adds a one-time event listener for the given event type.

.earlyOn(type, listener)

Prepends a listener for the given event type.

const emitter = new Emitter<{ hello: [string, number] }>()

emitter.on('hello', () => 1)
emitter.earlyOn('hello', () => 2)

const results = await emitter.emitAsPromise('hello')
// [2, 1]

.earlyOnce(type, listener)

Prepends a one-time listener for the given event type.

.emit(type[, data])

Emits the given event with optional data.

const emitter = new Emitter<{ hello: [string] }>()

emitter.on('hello', (event) => console.log(event.data))

emitter.emit('hello', 'John')

.emitAsPromise(type[, data])

Emits the given event with optional data, and returns a Promise that resolves with the returned data of all matching event listeners, or rejects whenever any of the matching event listeners throws an error.

const emitter = new Emitter<{ hello: [number, Promise<number>] }>()

emitter.on('hello', async (event) => {
  await sleep(100)
  return event.data + 1
})
emitter.on('hello', async (event) => event.data + 2)

const values = await emitter.emitAsPromise('hello', 1)
// [2, 3]

.emitAsGenerator(type[, data])

Emits the given event with optional data, and returns a generator function that exhausts all matching event listeners. Using a generator gives you granular control over what listeners are called.

const emitter = new Emitter<{ hello: [string, number] }>()

emitter.on('hello', () => 1)
emitter.on('hello', () => 2)

for (const listenerResult of emitter.emitAsGenerator('hello', 'John')) {
  // Stop event emission if a listener returns a particular value.
  if (listenerResult === 1) {
    break
  }
}

.listeners([type])

Returns the list of all event listeners matching the given event type. If no event type is provided, returns the list of all existing event listeners.

.listenerCount([type])

Returns the number of the event listeners matching the given event type. If no event type is provided, returns the total number of existing listeners.

.removeListener(type, listener)

Removes the event listener for the given event type.

.removeAllListeners([type])

Removes all event listeners for the given event type. If no event type is provided, removes all existing event listeners.