@zerodep/struct-eventemitter
TypeScript icon, indicating that this package has built-in type declarations

2.0.4 • Public • Published

@zerodep/struct-eventemitter

version language types license

CodeFactor Known Vulnerabilities

A factory function to add fully typed event emitter functionality to any object literal factory.

Full documentation is available at the zerodep.app page.

Examples

All @zerodep packages support both ESM and CJS.

import { eventEmitterFactory } from '@zerodep/struct-eventemitter';
// or
const { eventEmitterFactory } = require('@zerodep/struct-eventemitter');

Use Case

// define event:payload mapping
interface EventMap {
  userAdded: string;
  userRemoved: string;
}

// add the typed event emitter to your function factory
const userFactory = () => {
  // create the event emitter with the map
  const { on, first, once, off, emit } = eventEmitterFactory<EventMap>();

  return {
    addUser(userName: string) {
      // ... your logic do something with user (add to DB, etc...)

      // notify subscribers
      emit('userAdded', userName);
    },

    // add the event emitter methods
    on,
    once,
    off,
  };
};
const user = userFactory();

const myFunction = (data: string) => {
  console.log(data); // "janedoe"
};

user.on('userAdded', myFunction);
user.addUser('janedoe');

Package Sidebar

Install

npm i @zerodep/struct-eventemitter

Homepage

zerodep.app

Weekly Downloads

1

Version

2.0.4

License

MIT

Unpacked Size

9.19 kB

Total Files

7

Last publish

Collaborators

  • cdepage