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

fancy-emitter

v2.0.0

Published

A new take on JavaScript's EventEmitter class. Makes use of types and the newest JS features.

Downloads

361

Readme

Fancy Emitter

A new take on JavaScript's EventEmitter class. Makes use of types and the newest JS features.

This event emitter makes use of ES6 newset built in features, asynchronous functions and generators.

Comparison against Node.js 'events' module

| | fancy-emitter | Node.js events |-|-----------------|----------------- | Strongly Typed | ☑ | ☒ | Asynchronous | ☑ | ☒ | Iterable | ☑ | ☒ | Cancellable Events | ☑ | ☒ | Magic Events | ☒ | ☑ | Memory Leaks | ☒ | ☑

How to Use

Create a new emitter.

import {SafeEmitter} from 'fancy-emitter'
const action = new SafeEmitter<number>()

Set a listener on the action.

const value: number = await action.next

Or listen to many events which will occur.

let total = 0
for await (const value of action)
  total += value

Then activate the emitter whenever you please action.activate(12)

Emitters and their listeners can also be cancelled. To do this create an "unsafe" emitter instead.

import {Emitter} from 'fancy-emitter'
const cancellableAction = new Emitter<number>()

The loop listeners may be gracefully broken out of

cancellableAction.cancel()

or, with an error state by deactivating with the error

cancellableAction.deactivate(Error('err'))

Emitters can be merged with the helper.

import {SafeEmitter, Emitter, merge} from 'fancy-emitter'
const action = new SafeEmitter
const actionNumber = new Emitter<number>()

const merged = merge({ action, actionNumber })  // typeof merged == Emitter<
                                                // { name: "action" } |
                                                // { name: "actionNumber", value: number } >

Emitters can be cloned with the helper.

import {SafeEmitter, clone} from 'fancy-emitter'
const original = new SafeEmitter<string>()
const cloned = clone(original) // typeof SafeEmitter<string>

cloned.once(str => console.log(`Hello ${str}`))
original.activate('world')

Emitters can be filtered with the helper.

import {SafeEmitter, filter} from 'fancy-emitter'
const action = new SafeEmitter<string>()
const promise = filter(action, 'hello')

action.activate('hi')
action.activate('hey')
action.activate('hello') // promise is now resolved.

Emitters can be have listeners bound and later removed using the following helpers.

import {onceCancellable, onCancellable} from 'fancy-emitter'
const action = new Emitter<number>()
const cancel = onCancellable(action, console.log)

action.activate(1)
action.activate(2)
cancel()
action.activate(3) // not console.log'd

Classic

This can also be used like a classic event emitter with callbacks set to the on and once methods.

const action = new SafeEmitter<string>()

action.on(data => console.log(data))

action.activate('hello')
action.activate('world')

These listeners provide more functionality in that they can be cancelled.

const action = new Emitter<string>()

const cancel = action.onCancellable(data => console.log(data))
action.once(str => {
    if (str == 'world')
        cancel()
})

action.activate('hello')
action.activate('world')

action.activate('this will be shown')
setTimeout(() => action.activate("this won't. Since it occurs AFTER the cancel has time to propagate"))

Take a look at the tests for more examples.

API

The emitter is the union between a few interfaces.

  • A Listener (or SafeListener), which only detects when an event occurred.
interface Listener<T = void> extends AsyncIterable<T> {
    // Resolves when event is activated.
    // Rejects when event is deactivated or cancelled.
    readonly next: Promise<T>

    once(fn: OneArgFn<T>): Promise<void>
    on(fn: OneArgFn<T>): Promise<void>
}
  • A Broadcaster which can only trigger events.
interface SafeBroadcaster<T = void> {
    // Argument can be omitted iff arg is void.
    activate(arg: T): this
}
  • Or an "unsafe" Brodcaster which can also trigger errors.
interface Broadcaster<T = void> extends Broadcaster<T> {
    deactivate(err: Error): this
    cancel(): this
}

In the above interfaces the OneArgFn type refers to a function which takes an argument iff it isn't void. It uses an optional argument if a union with void and another value is present.

type OneArgFn<T> =
    Extract<T, void> extends never
        ? (arg: T) => void
        : Exclude<T, void> extends never
            ? () => void
            : (arg?: T) => void

Roadmap

This would be a shorthand for the fn function here.

try {
  for await (const _ of emitter);
} catch(err) {
  fn(err)
}

CDN

Use the CDN from unpkg!

<script src="//unpkg.com/fancy-emitter/dist/umd/index.js"></script>
<script>
  const {SafeEmitter} = emitter // The global variable `emitter` exposes the entire package.
</script>

Or as an ES module

<script type="module" src="//unpkg.com/fancy-emitter/dist/esm/index.js"></script>