Skip to content

Repository files navigation

mini-emit

visitorsnpm versionnpm downloadsbundleJSDocsLicense

📣 A minimal and strongly typed event emitter with no dependencies — just ~500 bytes gzipped!

This library reuses and extracts parts of the core implementation frommini-i18n. The original logic was refined and optimized for a standalone event emitter.

✨ Features

  • ✅ Type-safe event definitions
  • 📦 Zero dependencies and ultra-lightweight
  • 🧠 Simple API: on, off, once, emit, clear
  • 🧩 Can be used in both browser and Node.js environments
  • ⚙️ Ideal for internal module-level event handling

📦 Installation

Using npm:

npm install mini-emit

Using CDN:

<scriptsrc="https://cdn.jsdelivr.net/npm/mini-emit"></script><!-- or --><scriptsrc="https://unpkg.com/mini-emit"></script><script>constemitter=newminiemit.EventEmitter()</script>

🚀 Usage Example

import{EventEmitter}from'mini-emit'interfaceEvents{ready: voidmessage: stringdata: {id: number,name: string}}constemitter=newEventEmitter<Events>()// Subscribe to eventsconststop=emitter.on('message',(msg)=>{console.log('Got message:',msg)})// Emit eventsemitter.emit('ready')emitter.emit('message','Hello world')emitter.emit('data',{id: 1,name: 'Lete'})// One-time listeneremitter.once('ready',()=>{console.log('Only once!')})// Remove listenerstop()// Clear all listenersemitter.clear()// Clear specific event listenersemitter.clear('message')

🧩 API

new EventEmitter<T>()

Create a new event emitter instance with optional event type map.

on(event, listener): () => void

Add a listener to the specified event.

constoff=emitter.on('eventName',(payload)=>{})off()// Cancel the listener

once(event, listener): () => void

Listen to an event only once.

emitter.once('eventName',(payload)=>{console.log('Triggered only once')})

off(event, listener): void

Remove a specific listener.

emitter.off('eventName',listener)

emit(event, payload?): void

Emit an event with optional payload.

emitter.emit('eventName',data)

clear(event?): void

Clear all listeners or only listeners for a specific event.

emitter.clear()// Clear allemitter.clear('eventName')// Clear specific

🔧 Type Safety

With TypeScript, you can provide an EventMap type to get full type checking on event names and payloads.

interfaceEventMap{login: {userId: string}logout: void}constemitter=newEventEmitter<EventMap>()emitter.emit('login',{userId: 'abc123'})// ✅ OKemitter.emit('logout')// ✅ OKemitter.emit('logout','unexpected')// ❌ Type error

📄 License

MIT License © Lete114

About

A minimal and strongly typed event emitter with no dependencies

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages