npm

Bring the best of OSS JavaScript development to your projects with npm Orgs - private packages & team management tools.Learn more »

micromitter

1.0.4 • Public • Published

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 string
  • data 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'});

install

npm i micromitter

Downloadsweekly downloads

13

version

1.0.4

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability