Event-emitter with strong support for type hints
MIT License
Yes, this is another new js event library, why develop a new one? Let's first look at its advantages
npm i eveit
eveit.on('hello', (v) => {
console.log('Say ' + v);
});
eveit. emit('hello', 'Hi');
const e = new Eveit<{
aa: [string, number, ...any[]],
bb: [{a: string}],
}>();
e.on('aa', (a1, a2, a3) => {
// Here it will be inferred that a1 is string, a2 is number, a3 is any
});
e.on('bb', (v, v2) => {
v.a; // here it will be inferred that v is {a:string}
// v2 will report an error
});
e.on('cc', () => { // error, cc does not exist
});
e.emit('bb', {a: '1', b: 2}); // attribute b will report an error
const e = new Eveit();
e.on('hello', (v) => {
console.log('Say ' + v);
});
e. emit('hello', 'Hi');
class Test extends Eveit {
test () {
this.on('hello', () => {console.log('hello');});
this. emit('hello');
}
}
Generics + inheritance
class Test extends Eveit<{
aa: [string, number, ...any[]],
bb: [{a: string}],
}> {
//...
}
const a = {};
Eveit. bind(a);
a.on('hello', () => {console.log('hello');});
a. emit('hello');
binding + generics
const a: Eveit<{aa: [string]}> & {
[prop: string]: any;
} = {
};
Eveit. bind(a);
a.on('aa', (v) => {console.log('hello', v);});
a. emit('aa');
const e = new Eveit();
e.once('hello', (v) => {console.log('once', v);}); // Only trigger once
e.head('hello', (v) => {console.log('head', v);}); // Put the event in the head
e.headOnce('hello', (v) => {console.log('head', v);}); // combine the above two
const handler = (v) => {console. log(v);}
e.on('hello', handler);
e.off('hello', handler); // Remove a single event listener
e.clear('hello'); // Remove all listeners for the entire event
global open
Eveit.usePrevEmit = true;
Eveit. emit('hello', 'hi');
Eveit.on('hello', (v) => {console.log(v);});
turn on or off for an object
const e = new Eveit();
e.usePrevEmit = false;
e. emit('hello', 'hi');
e.on('hello', (v) => {console.log(v);}); // will not trigger hello
If you only want to trigger on static calls, you can write like this
Eveit._.usePrevEmit = true;