@zerodep/struct-eventemitter
v2.0.8
Published
A factory function to add event emitting capabilities to any object factory
Downloads
4
Readme
@zerodep/struct-eventemitter
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');