micromitter
v1.0.4
Published
minimal tiny and performant event emitter / dispatcher
Downloads
8
Maintainers
Readme
micromitter
minimal and performant event emitter / emitter with custom events and payload
API
Table of Contents
constructor
Creates an instance of MicroMitter.
Parameters
target
any the event target
on
adds an event handler to an event type
Parameters
Examples
emitter.on('type', (e)=>{
console.log(e);
});
Returns MicroMitter self
off
removes either a specific handler or all handlers related to an event type
Parameters
Returns MicroMitter self
once
adds an event handler to an event type and immediately removes it after first event call
Parameters
Examples
emitter.onc('type', (e)=>{
console.log('only once');
});
Returns MicroMitter self
emit
triggers an event for a specific type with an optional data object
Parameters
type
stringdata
any (optional, default{}
)
Examples
emitter.off('type', handler);
Returns MicroMitter self
Usage
import Emitter from 'micromitter';
const emitter = new Emitter();
emitter.on('test', (e)=>{
console.log(e.type === 'test');
console.log(e.foo === 'bar');
});
emitter.emit('test', {foo:'bar'});
emitter.off('test');
let counter = 0;
emitter.once('oneTime', (e)=>{
counter += 1;
});
emitter.emit('oneTime', {foo:'bar'});
emitter.emit('oneTime', {foo:'bar'});
emitter.emit('oneTime', {foo:'bar'});
emitter.emit('oneTime', {foo:'bar'});
console.log(counter); // 1
chaining
emitter
.on('type', handler)
.emit('type', {foo:'bar'})
.off('type', handler);
use global instance
import {emitter} from 'micromitter';
emitter.on('test', (e)=>{
console.log(e.type === 'test');
console.log(e.foo === 'bar');
});
emitter.emit('test', {foo:'bar'});
use decorator
import { micromitter } from 'micromitter';
//v1: use es7 decorators
@micromitter
class Tester {
onTest(e){
console.log(e.type === 'test');
console.log(e.foo === 'bar');
}
}
//v2 use the decorator as a function
micromitter(Tester);
const tt = new Tester();
tt.on('test', tt.onTest);
tt.emit('test', {foo:'bar'});