项目作者: soenkekluth

项目描述 :
minimal and performant event emitter / dispatcher
高级语言: JavaScript
项目地址: git://github.com/soenkekluth/micromitter.git
创建时间: 2017-08-18T05:08:46Z
项目社区:https://github.com/soenkekluth/micromitter

开源协议:

下载


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

  1. emitter.on('type', (e)=>{
  2. console.log(e);
  3. });

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

  1. emitter.onc('type', (e)=>{
  2. console.log('only once');
  3. });

Returns MicroMitter self

emit

triggers an event for a specific type with an optional data object

Parameters

  • type string
  • data any (optional, default {})

Examples

  1. emitter.off('type', handler);

Returns MicroMitter self

Usage

  1. import Emitter from 'micromitter';
  2. const emitter = new Emitter();
  3. emitter.on('test', (e)=>{
  4. console.log(e.type === 'test');
  5. console.log(e.foo === 'bar');
  6. });
  7. emitter.emit('test', {foo:'bar'});
  8. emitter.off('test');
  9. let counter = 0;
  10. emitter.once('oneTime', (e)=>{
  11. counter += 1;
  12. });
  13. emitter.emit('oneTime', {foo:'bar'});
  14. emitter.emit('oneTime', {foo:'bar'});
  15. emitter.emit('oneTime', {foo:'bar'});
  16. emitter.emit('oneTime', {foo:'bar'});
  17. console.log(counter); // 1

chaining

  1. emitter
  2. .on('type', handler)
  3. .emit('type', {foo:'bar'})
  4. .off('type', handler);

use global instance

  1. import {emitter} from 'micromitter';
  2. emitter.on('test', (e)=>{
  3. console.log(e.type === 'test');
  4. console.log(e.foo === 'bar');
  5. });
  6. emitter.emit('test', {foo:'bar'});

use decorator

  1. import { micromitter } from 'micromitter';
  2. //v1: use es7 decorators
  3. @micromitter
  4. class Tester {
  5. onTest(e){
  6. console.log(e.type === 'test');
  7. console.log(e.foo === 'bar');
  8. }
  9. }
  10. //v2 use the decorator as a function
  11. micromitter(Tester);
  12. const tt = new Tester();
  13. tt.on('test', tt.onTest);
  14. tt.emit('test', {foo:'bar'});