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

micro-typed-events

v1.0.2

Published

micro-typed-events

Downloads

686

Readme

micro-typed-events

NPM Build Status

const events = createEvents<number>();
const unsubscribe = events.subscribe(num => console.log(num));
events.emit(42);
events.emit(57);
unsubscribe();

events.emit(99); // not logged
events.emit('hey'); // not compiling

The smallest, most convenient, typesafe (with TS, but also works with normal JS), event emitter / pubsub system you'll ever need.

Unlike other event emitters, it does not use on/off/once methods but only a single subscribe method and returns an unsubscribe handle, which makes it more tiny, easier to type, more convenient to use with arrow functions.

The most minimal code you need for a typesafe pub/sub system, and feature complete, making suitable to include as a dependency on other libraries.

Install

npm install --save micro-typed-events
// or
yarn add micro-typed-events

Usage

Simple typed events

import { createEvents } from 'micro-typed-events';

const events = createEvents<number>();

const unsubscribe = events.subscribe(num => console.log(num));

events.emit(42);
events.emit('hey'); // Does not compile

unsubscribe();

Object typed events

import { createEvents } from 'micro-typed-events';

type EventType = { num: number; str: string };
const events = createEvents<EventType>();

const unsubscribe = events.subscribe(obj => console.log(obj));

events.emit({ num: 42, str: 'hello' });
events.emit({ num: 42, str: null }); // Does not compile

unsubscribe();

Multiple-args typed events

import { createEvents } from 'micro-typed-events';

const events = createEvents<number, string>();

const unsubscribe = events.subscribe((num, str) => console.log(num, str));

events.emit(42, 'hello');
events.emit('hello', 42); // Does not compile

unsubscribe();

Advanced typing, dynamic args...

import { createEvents } from 'micro-typed-events';

// Listener type is any void function
type ListenerType = (str: string, num: number, ...args: any[]) => void;

const events = createEvents<ListenerType>();

const unsubscribe = events.subscribe((str, num, ...args) =>
  console.log(str, num, ...args),
);

events.emit('hey', 1, 'blaa', 'whatever', 'you', 'want', 1, 2, 3);
events.emit(1, 'hey', 'blaa', 'whatever', 'you', 'want', 1, 2, 3); // Does not compile

unsubscribe();

Vanilla JS

import { createEvents } from 'micro-typed-events';

const events = createEvents();

const unsubscribe = events.subscribe(num => console.log(num));

events.emit(42);
events.emit('hey'); // Does not fail, you should use typescript

unsubscribe();

FAQ

Should I create a single events object for all my events?

No, you should rather create one per event-type. You could expose all your events as an object, like this:

export const ApiEvents = {
  requests: createEvents<Request>(),
  responses: createEvents<Response>(),
  errors: createEvents<Errors>(),
};

Can I unsubscribe directly inside a listener

Yes, listeners are able to unsubscribe themselves (or other listeners) without messing things up.

Can I subscribe directly inside a listener

Yes, but that listener will only be called on next emitted event.

Can I embed this library in my library?

Yes, this lib is very tiny. It exports ES and CJS modules. Here's the CJS output, I'll let you judge yourself if you can write something shorter:

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

function createEvents() {
    var listeners = [];
    return {
        subscribe: function (listener) {
            listeners.push(listener);
            return function () {
                var index = listeners.indexOf(listener);
                if (index > -1) {
                    listeners.splice(index, 1);
                }
            };
        },
        emit: function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            // take care of user trying to unsub inside a listener
            listeners.slice().forEach(function (listener) {
                if (listeners.indexOf(listener) > -1) {
                    listener.apply(void 0, args);
                }
            });
        },
    };
}

exports.createEvents = createEvents;
//# sourceMappingURL=index.js.map

License

MIT © slorber

Hire a freelance expert

Looking for a React/ReactNative freelance expert with more than 5 years production experience? Contact me from my website or with Twitter.