Supervised-EmitterSupervisedEmitter

Class: SupervisedEmitter

SupervisedEmitter is an event emitter library which supports middlewares, event-tracing, glob subscriptions etc

It's main applications can be found in State management, sagas, communication between component irrespective of whereever it is in the DOM tree

Hierarchy

  • SupervisedEmitter

Implements

Index

Constructors

Properties

Methods

Constructors

constructor

+ new SupervisedEmitter(middlewares: IMiddleware[], options: IOptions): SupervisedEmitter

Creates a new instance of SupervisedEmitter

Example

Initializing with no middlewares:

import SupervisedEmitter from 'supervised-emitter';

const SE = new SupervisedEmitter();

Initializing with middlewares and options:

const SE = new SupervisedEmitter(
  [eventTraceMiddleware],
  {debug: true, lfu: {max: 50}}
);

Parameters:

Name Type Default Description
middlewares IMiddleware[] [({ data }) => data] List of middlewares. Remember that all these middlewares will be piped to form a pipeline. i.e. the output of each of the middleware is passed in data(in the context) to the next middleware in the pipeline (top-down execution)
options IOptions {} Options for debugging and LFU

Returns: SupervisedEmitter

Properties

Static InternalEvents

InternalEvents: IInternalEvents = InternalEvents


Static patternHandler

patternHandler: patternHandler = patternHandler

Methods

getScope

getScope(): IGetScope

Implementation of ISupervisedEmitter

Adds scope to a event by prefixing it with a incrementing counter string(_scope_/), such that everytime this is called the subscribers can listen only on scoped events. This is especially useful when you don't want other subscribers to listen to this event. Then this behaves more like a camouflage event, which is visible only to scoped subscribers.

This is especially useful when multiple instances of the same class is listening and is interested only in events of its own instance.

Example

In React, if you're using the same component in multiple places but your actions(Show popup, make a request etc) are different in each place, then you may achieve it like this:

/// container.jsx
const [{scope}] = useState({scope: SE.getScope()});

SE.subscribe(scope('btn/click'), ({data}) => {
  // ...
});

<ChildComponent scope={scope} />

/// In ChildComponent.jsx
SE.publish(this.props.scope('btn/click'),  data)

Returns: IGetScope

Function(Closure) that can add scope to events


publish

publish(pubEvent: string, data: any): Promise‹any›

Implementation of ISupervisedEmitter

Publishes the given event to all the matching subscribers.

NOTE: This is an asynchronous call, so if you want to publish events one after the other, then you will have to await on each publish call. Please see the example below for more details.

Example

Simple publish (fire and forget):

SE.publish('foo/bar', 1);

SE.publish('foo/bar', 'hello world');

Publish one after the other (execute all the subscription pipelines before moving to next publish):

await SE.publish('publish/first', 'first');

// This will be published only after all the
// matching subscription pipelines of the above
// publish events have been completed
await SE.publish('publish/second', 'second');

Parameters:

Name Type Default Description
pubEvent string - Event to publish the given data
data any null Any data that need to be published

Returns: Promise‹any›

Awaitable publish


subscribe

subscribe(event: string, ...handlers: IHandler[]): ISubscription

Implementation of ISupervisedEmitter

Subscribes to a given event and pipes all the handlers passed for this event.

Please note that each handler must pass on the data that must be handled by the next handler, as all these handlers will be piped (compose in reverse direction).

Chaining subscriptions is also possible. Please see the example below for more details.

For more info on pipe visit: https://medium.com/free-code-camp/pipe-and-compose-in-javascript-5b04004ac937

Example

const subscription = SE.subscribe('foo/bar',
  ({data}) => {
    console.log(data); //=> 1
    return data + 1,
  },
  ({data}) => {
    console.log(data); //=> 2
  }
).subscribe('foo/*',
  ({data}) => console.log(data) //=> 1
);

await SE.publish('/foo/bar', 1);

subscription.unsubscribe();

Parameters:

Name Type Description
event string Subscription event
...handlers IHandler[] List of handlers

Returns: ISubscription

Subscription for chaining more subscriptions or for unsubscribing from all the subscriptions


subscribeOnce

subscribeOnce(event: string, ...handlers: IHandler[]): Promise‹any›

Implementation of ISupervisedEmitter

Similar to subscribe, but it listens only to the first event and unsubscribes itself thereafter.

Example

let calls = 0;
const subscription = SE.subscribeOnce('foo/bar', () => calls++)

await SE.publish('/foo/bar', 'test');
await SE.publish('/foo/bar', 'test');

console.log(calls) //=> 1

subscription.unsubscribe();

Parameters:

Name Type Description
event string Subscription event
...handlers IHandler[] List of handlers

Returns: Promise‹any›

Subscription for chaining more subscriptions or for unsubscribing from all the subscriptions


unScope

unScope(event: string): string

Implementation of ISupervisedEmitter

Strips out the scope part in the given scoped event.

i.e, it converts _scope_/foo/bar => foo/bar

This method can be used in your middlewares to unshell the scope part in the topic and run your logics.

Parameters:

Name Type Description
event string Scoped event

Returns: string

Event without scope part


waitTill

waitTill(event: string): Promise‹any›

Implementation of ISupervisedEmitter

Waits untill the required event is received. This is especially useful when writing flows of execution.

Example In a request life-cycle if some action needs to be take post a response has been received, then it can be written as follow

SE.publish('req/profiles/load')
await SE.waitTill('req/profiles/success')

SE.publish('req/profiles/sort')

Parameters:

Name Type Description
event string Subscription event

Returns: Promise‹any›

a Promise that resolves to data

results matching ""

    No results matching ""