npm.io
2.0.0 • Published 5 years ago

publisher-subscriber-ts

Licence
ISC
Version
2.0.0
Deps
1
Size
19 kB
Vulns
1
Weekly
0

publisher-subscriber-ts

Publisher subscriber library for javascript.

Setup

  1. npm install
  2. npm run prepare

Prepare will build this project and create a lib folder which'll contain publisher.min.js for consumption. It'll also create a ES6 version called publisher.es.js and couple of declaration files.

Running test

  1. npm run test

This will execute Jest on project.

Usage

  • This package has concept of Publisher and Subscriber

  • A Publisher communicates with all it's Subscriber through something called Topic

  • A Publisher can create any number of Topic and emit event/data to each Topic

  • A Subscriber can subscribe/listen to any number of Topic by providing a callback function

  • A Subscriber can unsubscribe any Topic at any given time

Example

1. Creating a Topic

// @class Publisher has static helper methods
const  topic1  =  Publisher.createTopic("Topic 1");
2. Subscribing a Topic
// Subscription option takes topic name and optional 'getLastValue' flag which indicates if subscriber should reveice last emitted value from topic
const  subscriptionOption  = {
	topicName: "Topic 1",
	getLastValue: true
};

// @class Publisher has static helper methods
const  subscription1  =  Publisher.subscribeTopic(subscriptionOption, (event) => {
	console.log('Callback function event: ', event);
});
3. Emitting date from topic
const  event  = {
	data: 'Some random data to be broadcasted'
};

// We use object created from "Publisher.createTopic()"
topic1.publish(event);
4. Unsubscribing a Topic
// @class Publisher has static helper methods. Pass subscription object to be unsubscribed.
Publisher.unsubscribeTopic(subscription1);

Documentation

1. @class Publisher
Method Description
createTopic(topicName: string) Creates new topic for given topic name
subscribeTopic(option: SubscribeOption, callback: Function): Subscriber Subscribe to a particular topic by providing option and a callback function
unsubscribeTopic(subscriber: Subscriber) Unsubscribe any given subscriber
2. @class Subscriber
Method Description
callBack Getter for returning callback function
id Getter for returning subscrber ID
topicName Getter for returning topic name
3. @class Topic
Method Description
publish(event: any) Publish any event for current topic. Once event is published all active subscribers will get a notification in callback function
unsubscribe(subscription: Subscriber) Method to unsubscribe/remove a listener of this topic
topicName Getter for returning topic name
4. @interface SubscribeOption
Property Description
topicName Required string option to pass name
getLastValue Optional boolean flag to indicate if last emitted value from topic should be re-emitted for given subscriber only. Default value is false

Keywords