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

inf-ee

v1.0.4

Published

Type Safe EventEmitter

Downloads

301

Readme

Type Safe Event Emitter

Simple event emitter for any Javascript runtime environment (browser, nodejs, etc...). Uses Typescript's type inference feature to provide type safety for consumer and producer.

Table of contents

TL;DR

import {EventEmitter} from "inf-ee";

type EventSet = {
    data: (str: string) => void
}
const ee = new EventEmitter<EventSet>();
ee.on(`data`, (data) => {
    console.log(`Received data: ${data.toUpperCase()}`);
});
ee.emit(`data`, `Important info`);

Installation

Command line

$ npm install --save inf-ee

CDN

https://unpkg.com/inf-ee@latest/dist/browser/event-emitter.min.js

Usage

Typescript

import {EventEmitter} from "inf-ee";

type EventSet = {
    data: (str: string) => void
}
const ee = new EventEmitter<EventSet>();
ee.on(`data`, data => {
    console.log(`Received data: ${data.toUpperCase()}`);
});
ee.emit(`data`, `Important info`);

NodeJS

const EventEmitter = require('inf-ee').EventEmitter;

const e = new EventEmitter();

e.on('greet', function (name) {
    console.log(`Hi, ${name}`);
});

e.emit('greet', 'John');

ES6 Modules

import { EventEmitter } from "inf-ee";

const e = new EventEmitter();

e.on('data', data => console.log(data));

e.emit('data', 'Data chunk');

Browser

<script src="//unpkg.com/inf-ee@latest/dist/browser/event-emitter.min.js"></script>
<script>
    var ee = new InfEE();
    ee.on('greet', function (name) {
        console.log('Hi, ' + name);
    });
    ee.emit('greet', 'John');
</script>

Producer / Consumer example

producer.ts

  1. Producer constructs a type EventSet with a set of properties EventName of type Event Handler.
  2. Producer exposes on, once, off methods for consumer in order to subscribe / unsubscribe to internal events.
  3. Producer emits events passing the supplied arguments to each handler.
// ----- producer.ts

import {EventEmitter} from "inf-ee";

type MathAction = 'multiplication' | 'division';

type EventSet = {
    mathAction: (action: MathAction, oldValue: number, newValue: number) => void
    error: (err: string) => void
}

export class NumberManipulation {
    private _ee = new EventEmitter<EventSet>();

    constructor(private _num = 0) {}

    multiplication(n: number) {
        const old = this._num;
        this._num *= n;
        this._ee.emit('mathAction', 'multiplication', old, this._num);
        return this;
    }

    division(n: number) {
        if(n === 0) {
            this._ee.emit('error', `Can't divide by zero`);
            return this;
        } else {
            const old = this._num;
            this._num /= n;
            this._ee.emit('mathAction', 'division', old, this._num);
            return this;
        }
    }

    on<EventName extends keyof EventSet>(eventName: EventName, handler: EventSet[EventName]) {
        this._ee.on(eventName, handler);
    }

    once<EventName extends keyof EventSet>(eventName: EventName, handler: EventSet[EventName]) {
        this._ee.once(eventName, handler);
    }

    off<EventName extends keyof EventSet>(eventName: EventName, handler: EventSet[EventName]) {
        this._ee.off(eventName, handler);
    }
}

consumer.ts

  1. Consumer subscribes to events.
  2. Consumer invokes object's methods and gets notified.
// ----- consumer.ts

import { NumberManipulation } from "./NumberManipulation";

const m = new NumberManipulation(1);

m.once('mathAction', () => {
    console.log(`I run only once`);
});
m.on('mathAction', (action, oldValue, newValue) => {
    console.log(`${action}: Old value is ${oldValue}. New value is ${newValue}`);
});
m.on('error', err => {
    console.log(`Error! ${err}`);
});

m.multiplication(2).multiplication(6).division(3).division(0);

output

I run only once
multiplication: Old value is 1. New value is 2
multiplication: Old value is 2. New value is 12
division: Old value is 12. New value is 4
Error! Can't divide by zero

API Reference

# on(eventName: string | symbol | number, handler: Function) : void

Adds the handler to the end of the listeners array for the eventName. No checks are made to see if the handler has already been added. Multiple calls passing the same combination of eventName and handler will result in the listener being added, and called, multiple times.


# once(eventName: string | symbol | number, handler: Function) : void

Adds a one-time handler function for the eventName. The next time eventName is triggered, this handler is invoked and then removed.


# off(eventName: string | symbol | number, handler: Function) : void

Removes the specified handler from the listener array for the eventName. If the handler has been added multiple times, then all references of that handler will be removed.


# offByName(eventName: string | symbol | number) : void

Removes all handlers, or those of the specified eventName. It's bad practice. Use on own risk.


# offAll() : void

Removes all handlers of all events. It's bad practice. Use on own risk.


# has(eventName: string | symbol | number, handler: Function): boolean

Checks whether a handler has been attached to eventName


# emit(eventName: string | symbol | number, ...args: Parameters<Function>): void

Synchronously calls each of the handlers registered for the eventName, in the order they were registered, passing the supplied ...args to each.

Tests

This module is well tested. You can run tests by executing the following command.

$ npm run test

LICENSE

MIT