minimal and performant event emitter / emitter with custom events and payload
Creates an instance of MicroMitter.
Parameters
target
any the event target
adds an event handler to an event type
Parameters
Examples
emitter.on('type', (e)=>{
console.log(e);
});
Returns MicroMitter self
removes either a specific handler or all handlers related to an event type
Parameters
Returns MicroMitter self
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
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
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
emitter
.on('type', handler)
.emit('type', {foo:'bar'})
.off('type', handler);
import {emitter} from 'micromitter';
emitter.on('test', (e)=>{
console.log(e.type === 'test');
console.log(e.foo === 'bar');
});
emitter.emit('test', {foo:'bar'});
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'});