pub-sub-map
v1.0.0
Published
A minimal, namespaced pub-sub implementation with optional data storing on publish and data retrieval on subscribe.
Downloads
54
Maintainers
Readme
pub-sub-map
A minimal, namespaced pub-sub implementation with optional data storing on publish and data retrieval on subscribe.
Installation
npm install pub-sub-map
Usage
import pubSubMap from "pub-sub-map";
const ON = "on";
const OFF = "off";
const NAMESPACE = "LIGHT";
const pubSub = pubSubMap.get(NAMESPACE);
// Listen for light state (before any pubish())
const unsubscribe = pubSub.subscribe("switch", (value) => {
console.log(value);
// 1. => value === ON
});
// 1. Turn the light on, storing the value
pubSub.publish("switch", ON, true);
// Unsubscribe the first callback
unsubscribe();
// Listen for light state and retrieve the current state immediately (callback on subscribe() and subsequent publish())
pubSub.subscribe(
"switch",
(value) => {
console.log(value);
// 1. => value === ON
// 2. => value === OFF
},
true,
);
// Listen for light state without checking current state (callback on subsequent publish)
pubSub.subscribe("switch", (value) => {
console.log(value);
// => 2. value === OFF
});
// 2. Turn the light off
pubSub.publish("switch", OFF, true);
API
Modules
Classes
pub-sub-map
Summary: Export a PubSubMap instance.
pub-sub-map.exports.PubSub : PubSub
Create a world object to store entities and systems.
Kind: static class of pub-sub-map
pub-sub-map.exports.PubSubMap : PubSubMap
Extend a Map object to automate getting a namespaced PubSub instance on pubSubMap.get(namespace).
Kind: static class of pub-sub-map
PubSub
Kind: global class
pubSub.publish(type, value, store)
Broadcast value to all subscribers identified by "type". Optionally store it for subsequent subscribers to retrieve it immediately.
Kind: instance method of PubSub
| Param | Type | | ----- | -------------------- | | type | string | | value | * | | store | boolean |
pubSub.subscribe(type, cb, retrieve) ⇒ function
Listen for published update identified by "type". Optionally retrieve the current state on creation (ie. call cb(storedValue)).
Kind: instance method of PubSub Returns: function - Call to stop listening.
| Param | Type | | -------- | --------------------- | | type | string | | cb | function | | retrieve | boolean |
PubSubMap
Kind: global class
pubSubMap.get(key) ⇒ PubSub
Get a namespaced instance of PubSub.
Kind: instance method of PubSubMap
| Param | Type | Description | | ----- | ------------------- | ----------------------------------------------------- | | key | string | The key of the element to return from the Map object. |
License
MIT. See license file.