- Javascript implementation of publisher subscriber pattern
- Can be used with various event emitters including browser's window object
- Provides Publisher class
npm i publisher-subscriber-pattern
The example uses the browser's window object as emitterInstance. Other valid emitter instances can be also used.
import { Publisher } from 'publisher-subscriber-pattern';
const publisher = new Publisher(window, 'addEventListener','removeEventListener');
Publisher's subscribe method returns function, which can be used later to unsubscribe from the publisher's event.
const unsubscribe = publisher.subscribe('scroll', (event) => {});
// ...foo code...
unsubscribe();
There is also a method unsubscribeAll for unsubscribing all subscribers from all emitter's events.
publisher.unsubscribeAll();
- Parameters: emitterInstance, addListenerMethodName, removeListenerMethodName
- Methods: subscribe, unsubscribeAll, eventSubscribersCount, subscribersCount
- Object, which exposes addListener and removeListener methods
- Behind the scenes, the emitterInstance is bound to addListener and removeListener methods as this (see Function.prototype.bind)
- Names of methods (strings), which are exposed by emitterInstance and, which add and remove event listeners, respectively
-
Required parameters: eventName, eventCallback
-
Optional parameter: subscriberInstance, which will be bound to the eventCallback argument as this (see Function.prototype.bind)
-
Method subscribes eventCallback to eventName, so whenever event occurs the eventCallback is called
-
Returns function for unsubscribing from the event
- Unsubscribes all publisher's eventCallbacks from all emitter's eventNames
- Required parameter: eventName
- Returns number of subscribers' eventCallbacks subscribed to publisher's eventName
- Returns number of subscriber's eventCallbacks subscribed to all publisher's eventNames
- Package has no production dependencies
- Typescript
- Jasmine, chai, sinon
- Babel
- Node (EventEmitter)