Implementation of the pub-sub pattern.
-
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>
-
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');
-
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 });