1.0.0 • Published 8 months ago

pub-sub-map v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

pub-sub-map

npm version stability-stable npm minzipped size dependencies types Conventional Commits styled with prettier linted with eslint license

A minimal, namespaced pub-sub implementation with optional data storing on publish and data retrieval on subscribe.

paypal coinbase twitter

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

ParamType
typestring
value*
storeboolean

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.

ParamType
typestring
cbfunction
retrieveboolean

PubSubMap

Kind: global class

pubSubMap.get(key) ⇒ PubSub

Get a namespaced instance of PubSub.

Kind: instance method of PubSubMap

ParamTypeDescription
keystringThe key of the element to return from the Map object.

License

MIT. See license file.

1.0.0

8 months ago