Skip to content
JavaScript/TypeScript pubsub implementation
TypeScript JavaScript
Branch: master
Clone or download

Latest commit

Fetching latest commit…
Cannot retrieve the latest commit at this time.

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github added observable Dec 28, 2019
src
tests
.eslintrc conversion to typescript module Nov 25, 2019
.gitignore
.npmignore
.prettierrc
LICENSE
README.md added on onPublish config to the API Mar 6, 2020
bundlesize.config.json changes Jan 25, 2020
jest.config.js
package-lock.json more changes to the configuration Jan 25, 2020
package.json
tsconfig.json

README.md

Pubbel

Node version NPM Downloads Minified size License: MIT

Pubbel is a very light-weight JavaScript library that makes it possible to subscribe to changes without depending on a framework. It relies on a publish-subscribe implemementation for asynchronous communication between for instance UI components, observables for specific values and queues when many changes happen but cannot be processed, yet. This package helps you process actions in the background that have nothing to do with your UI.

Pub/Sub

A pubsub can be created by using the pubbel function. Optionally, you can turn on syncing between browser windows by adding a configuration object as a parameter to the pubbel function.

import { pubbel } from 'pubbel';
const pubsub = pubbel();
const pubsub = pubbel({ enableBrowserTabSync?: true, onPublish?: (message) => myFn(message) });

You subscribe to a topic by using the subscribe(message: String, callback: Function) function. This returns a Function. This function can be used to remove it from pubbel. The callbacks can either be synchronous or asynchronous.

function myFunction(...args) { ... }
const removeSubscription = pubsub.subscribe('message-1', myCallback);
removeSubscription();

Publishing a message on your pubsub can be done by using the publish(message, ...args) function. Removing a topic completely from the pubsub can be done with the delete(message) function.

pubsub.publish('message-1');
pubsub.publish('message-2', data);
pubsub.delete('message-1');

Observable - subscribe to value changes

An observable makes it possible to observe changes to a particular value, and execute one or more functions when the value changes.

import { observable } from 'pubbel';

const myObservable = observable('start');
console.log(myObservable.get()); // 'start'
observable.set('second');
console.log(observable.get()); // 'second'

You can subscribe/listen to changes by using the subscribe function of the observable.

let count = 0;
const myFunction(value) => count++;

myObservable.subscribe(myFunction);
myObservable.set('second');
console.log(count); // 1

Each subscribe gives back a Function. This function can be used to unsubscribe to the observable, if required.

const remove = myObservable.subscribe(myFunction);
remove();
You can’t perform that action at this time.