JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • 0
  • Score
    100M100P100Q27896F
  • License MIT

minimal tiny and performant event emitter / dispatcher

Package Exports

  • micromitter

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (micromitter) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

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