1.0.1 • Published 4 years ago

@xunmi/event-channel v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

event-channel

ci codecov npm bundle size npm version

Implementation of the pub-sub pattern.

Install

  • NPM

    npm install --save @xunmi/event-channel
    # or
    yarn add @xunmi/event-channel
    import EventChannel from '@xunmi/event-channel';
  • CDN

    <script src="https://cdn.jsdelivr.net/npm/@xunmi/event-channel@1/dist/event-channel.umd.min.js"></script>

Basic Usage

  • Get instance

    const eventChannel = new EventChannel();
  • Subscribe to an event

    const subscriber = (...params) => {
    	// do something 
    }
    // support `string` or `symbol` type
    eventChannel.on('foo', subscriber);
  • Subscribe to a one-time event

    eventChannel.once('foo', subscriber);
    		```
  • Dispatch an event

    eventChannel.emit('foo', ...params);
  • Unsubscribe to an event

    eventChannel.off('foo', subscriber);
    
    // unsubscribe all about 'foo'
    eventChannel.off('foo');

Other Usage

  • Binding context

    eventChannel.on('foo', subscriber, { context: this });
  • Publish before subscribe

    // set `before` is event type or `true`
    const eventChannel = new EventChannel({ before: ['foo'] });
    
    // set `before` is `true`
    eventChannel.on('foo', subscriber, { before: true });