ton.emit
v2.0.2
Published
一个事件管理工具
Maintainers
Readme
TonEmitter
A lightweight and fully type-safe Event Emitter for JavaScript / TypeScript, supporting:
- Priority-based listeners
- Once-only listeners
- Listener IDs for replacement
- Synchronous and asynchronous listeners
- Attach emitter methods (
on,off,once,emit,clear) directly to any class instance - Full TypeScript generic support for event names and parameters
Installation
# npm
npm install ton.emit
# yarn
yarn add ton.emitUsage (JavaScript)
import { TonEmitter } from 'ton.emit';
const emitter = new TonEmitter();
// Regular listener
emitter.on('event1', data => {
console.log('event1 received', data);
});
// Once listener
emitter.once('event2', () => console.log('event2 fired once'));
// Emit events
emitter.emit('event1', 123);
emitter.emit('event2');
emitter.emit('event2'); // will not fire
// Remove listener
const handler = data => console.log(data);
emitter.on('event3', handler);
emitter.off('event3', handler);
// Clear events
emitter.clear('event1'); // clear specific
emitter.clear(); // clear allUsage (TypeScript, Type-Safe)
import { TonEmitter } from 'ton.emit';
interface MyEvents {
login: [string]; // username
logout: []; // no arguments
dataUpdate: [number, string]; // id, value
}
class MyService {
constructor() {
// Automatically attach emitter methods to this
this.emitter = new TonEmitter<MyEvents>(this);
}
doStuff() {
// Type-safe event registration
this.on('login', username => {
console.log('User logged in:', username);
});
this.emit('login', 'Alice'); // ✅ correct
// this.emit('login', 123); ❌ TypeScript will report error
}
}API
new TonEmitter(target?: object)
target(optional): If provided, automatically attacheson,off,once,emit,clearmethods to the object.
on(eventName, listener, options?)
Registers a listener.
eventName: string | keyof Eventslistener: function to handle eventoptions:id(optional): unique ID for the listener, allows replacementpriority(optional, default 0): higher priority listeners are executed first
once(eventName, listener, options?)
Registers a listener that executes only once.
off(eventName, identifier)
Removes listener(s) by:
- function reference
{ fn }object- listener ID string
emit(eventName, ...args)
Triggers event, returning an array of results. Automatically handles async listeners with Promise.all.
clear(eventName?)
- Clears a specific event if
eventNameprovided, otherwise clears all events.
attachTo(target, methods?)
- Attach emitter methods to any object.
methods(optional): array of method names to attach (default['on','off','once','emit','clear']).
Features
- Fully TypeScript typed, supports generics for event names and listener argument types.
- Priority-based listener execution.
- Listener replacement by ID.
- Works with sync and async listeners.
- Can inject emitter methods directly into other classes for easy usage.
License
MIT
