Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

pubst

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pubst - npm Package Compare versions

Comparing version 0.2.0 to 0.2.1

3

CHANGELOG.md

@@ -0,1 +1,4 @@

## v0.2.1 - Apr 27 2018
+ Adds documentation
## v0.2.0 - Mar 08 2018

@@ -2,0 +5,0 @@ + Adds `doPrime` subscription configuration option

@@ -5,4 +5,5 @@ 'use strict';

/*
/**
* Pubst - Basic JavaScript Pub/Sub Event Emitter
* @module pubst
*

@@ -56,2 +57,9 @@ * Copyright 2017 Jason Schindler

/**
* Set global configuration.
* @param {Object} config - Your configuration
*
* Available options are:
* `showWarnings` (default: true) - Show warnings in the console.
*/
function configure() {

@@ -134,2 +142,7 @@ var userConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

/**
* Publish to a topic
* @param {string} topic - The topic to publish to
* @param {*} payload The payload to publish
*/
function publish(topic, payload) {

@@ -148,2 +161,32 @@ store[topic] = payload;

/**
* Subscribe to one or more topics
* @param {string|RegExp} topic - The topic to receive updates for
* @param {Function|Object} handler
* @param {*} default - (Optional) Value to send when topic is empty
*
* @returns {Function} - A function that will remove this
* subscription from getting further updates.
*
* The first argument may be a string or a regular expression.
* If a string is provided, the handler will be called for all
* updates for that topic. If a regular expression is provided,
* the handler will be called for all topics that match the regular
* expression.
*
* The second argument may be a function or an object. The object
* is necessary if you want to provide configuration options for
* this subscription. Available options are:
*
* `default` - (Default: undefined) - Default value for this sub.
* `doPrime` - (Default: true) - Should the handler be primed with
* the last value?
* `allowRepeats` - (Default: false) - Should the handler be called
* when the value doesn't change
* `handler` - (Required) - The handler to call.
*
* The handler will be called on topic updates. It will be passed
* the new value of the topic as the first argument, and the name of
* the topic as the second argument.
*/
function subscribe(topic, handler, def) {

@@ -202,2 +245,9 @@ var subscription = {

/**
* Get the current value of a topic.
* @param {string} topic - The topic to get the value of.
* @param {*} default - (Optional) a value to return if the topic is
* empty.
* @returns {*} - The current value or the default
*/
function currentVal(topic, def) {

@@ -207,2 +257,8 @@ return valueOrDefault(store[topic], def);

/**
* Clears a given topic.
* @param {string} topic - The topic to clear
*
* Clears the topic by publishing a `null` to it.
*/
function clear(topic) {

@@ -214,2 +270,5 @@ if (store.hasOwnProperty(topic)) {

/**
* Clears all known topics.
*/
function clearAll() {

@@ -216,0 +275,0 @@ Object.keys(store).forEach(clear);

8

package.json
{
"name": "pubst",
"version": "0.2.0",
"version": "0.2.1",
"description": "A slightly opinionated pub/sub event emitter for JavaScript.",

@@ -37,7 +37,7 @@ "main": "lib/pubst.js",

"clear-require": "2.0.0",
"eslint": "4.18.2",
"mocha": "5.0.4",
"sinon": "4.4.2",
"eslint": "4.19.1",
"mocha": "5.1.1",
"sinon": "4.5.0",
"sinon-chai": "3.0.0"
}
}

@@ -5,11 +5,198 @@ # Pubst

I suggest that you **DO NOT** use this for anything terribly serious just yet. I'm still kind of feeling it out myself.
Pubst is a slightly opinionated pub/sub library for JavaScript.
This is yet another basic asynchronous pub/sub implementation in JavaScript. I almost used [PubSubJS](https://github.com/mroderick/PubSubJS), but there are a few features I wanted that it doesn't support. I may try and add those in so I don't need to maintain this lib ;-). The features I wanted in a pub/sub lib (in order of importance) are:
+ Prime subscribers with latest payload even if it occurred before the subscription.
+ Allow subscribers to define default payloads to be sent in the event of an empty or `null` publish.
+ Warnings when publishing to a topic that has no subscribers.
Like many other JavaScript pub/sub libraries, Pubst acts as a single central broker for any number of topics.
You can publish to a topic in one component/class/module and any other component/class/module that has subscribed to that topic will receive a call with the updated payload.
## TODO (In no particular order)
+ Use this in a few things to feel out the API.
+ If I'm going to continue to use this implementation, I should probably write actual documentation.
Pubst has a few other features worth noting:
+ Subscribers can register a default value to receive in the event that their topic does not have a value set or has a value of `null`.
+ By default, subscribers are primed with the last value published on the topic (or their default).
+ By default, subscribers will not receive subsequent calls when the same value is published to a topic more than once.
+ A subscriber can listen for updates to a given topic, or can provide a regular expression that matches the strings of all topics they would like to receive updates for.
## Basic Usage
```js
// File1.js
const pubst = require('pubst');
pubst.subscribe('NAME', name => {
console.log(`Hello ${name}!`);
}, 'World');
```
Because the subscriber passed a default value of 'World' and the topic is currently empty, the subscriber is primed with the default value.
```
Hello World!
```
When another module publishes 'Jill' on the 'NAME' topic, the subscriber is called with the new value.
```js
// File2.js
const pubst = require('pubst');
pubst.publish('NAME', 'Jill');
```
```
Hello Jill!
```
If the topic is cleared, the subscriber is again called with their default value.
```js
pubst.clear('NAME');
```
```
Hello World!
```
Each subscriber is free to define their own default for each topic.
## API
### `configure(configOptions)`
Sets global Pubst configuration.
#### Available options:
+ `showWarnings` (default: true) - Show warnings in the console.
#### Example
```js
pubst.configure({showWarnings: false});
```
### `publish(topic, payload)`
Publishes a value to a topic.
Topic names are expected to be strings.
Payloads should be treated as immutable.
#### Examples
```js
pubst.publish('SELECTED.COLOR', 'blue');
pubst.publish('current.user', {
name: 'Some User',
permissions: [
'BORING.THINGS.VIEWER'
]
});
```
**NOTE:** Mutating payloads received by a subscriber is a really bad idea.
You may be changing data that other portions of your application are using.
This is likely to result in terrible bugs that are difficult to find.
### `subscribe(topic, handler|subscriptionConfig[, defaultValue])`
Registers a subscriber to one or more topics
The first argument may be a string or a regular expression.
If a string is provided, the handler will be called for all updates for that topic.
If a regular expression is provided, the handler will be called for all topics that match the regular expression.
The second argument may be a handler function that is called when updates are published to the topic, or a configuration object for the subscription.
The configuration object is necessary if you want to change default configuration options for this subscription.
Available options are:
+ `handler` - (Required) - The handler to call when the topic is updated.
+ `default` - (Default: undefined) - Default value for this sub.
+ `doPrime` - (Default: true) - Should the handler be primed with the last value?
+ `allowRepeats` - (Default: false) - Should the handler be called when the value doesn't change?
The handler will be called on topic updates.
It will be passed the new value of the topic as the first argument, and the name of the topic as the second argument.
#### Example 1 - Basic usage
```js
pubst.subscribe(
'SELECTED.COLOR', // The topic you are subscribing to
color => { // A handler function
doSomethingWithColor(color);
},
'red' // Default value
);
```
#### Example 2 - Multiple topics
```js
pubst.subscribe(
/SELECTED.*/, // This matches all strings that start with 'SELECTED'
(payload, topic) => { // A handler function
if (topic === 'SELECTED.COLOR') {
doSomethingWithColor(payload);
} else if (topic === 'SELECTED.FOOD') {
doSomethingWithFood(payload);
}
},
'EMPTY' // Default value
);
```
#### Example 3 - Subscription Configuration
```js
pubst.subscribe(
'SELECTED.COLOR', // The topic you are subscribing to
{
// The handler
handler: color => (doSomethingWithColor(color)),
// Default value
default: 'red',
// Do not prime the handler with the last value on subscribe
doPrime: false,
// Call the handler even when published value did not change
allowRepeats: true
}
);
```
### `currentVal(topic[, defaultValue])`
Gets the current value of a topic.
If a defaultValue is provided and the topic is currently `undefined` or `null`, the defaultValue will be returned.
#### Example
```js
const color = pubst.currentVal('SELECTED.COLOR', 'red');
```
### `clear(topic)`
Clears a given topic by publishing a `null` to it.
Subscribers that provided a default value will receive their default.
#### Example
```js
pubst.clear('SELECTED.COLOR');
```
### `clearAll()`
Clears all known topics.
#### Example
```js
pubst.clearAll();
```
## Future Plans
In the not-so-far future I would like to:
1. Add hooks for persistence strategies.
2. Experiment with creating a React library that makes linking topics with props mostly painless.
3. Add topic-wide configuration (like: defaults)

@@ -1,3 +0,4 @@

/*
/**
* Pubst - Basic JavaScript Pub/Sub Event Emitter
* @module pubst
*

@@ -19,3 +20,2 @@ * Copyright 2017 Jason Schindler

(function (root, factory) {

@@ -47,2 +47,9 @@ if (typeof define === 'function' && define.amd) {

/**
* Set global configuration.
* @param {Object} config - Your configuration
*
* Available options are:
* `showWarnings` (default: true) - Show warnings in the console.
*/
function configure(userConfig = {}) {

@@ -117,2 +124,7 @@ for (const key in userConfig) {

/**
* Publish to a topic
* @param {string} topic - The topic to publish to
* @param {*} payload The payload to publish
*/
function publish(topic, payload) {

@@ -131,2 +143,32 @@ store[topic] = payload;

/**
* Subscribe to one or more topics
* @param {string|RegExp} topic - The topic to receive updates for
* @param {Function|Object} handler
* @param {*} default - (Optional) Value to send when topic is empty
*
* @returns {Function} - A function that will remove this
* subscription from getting further updates.
*
* The first argument may be a string or a regular expression.
* If a string is provided, the handler will be called for all
* updates for that topic. If a regular expression is provided,
* the handler will be called for all topics that match the regular
* expression.
*
* The second argument may be a function or an object. The object
* is necessary if you want to provide configuration options for
* this subscription. Available options are:
*
* `default` - (Default: undefined) - Default value for this sub.
* `doPrime` - (Default: true) - Should the handler be primed with
* the last value?
* `allowRepeats` - (Default: false) - Should the handler be called
* when the value doesn't change
* `handler` - (Required) - The handler to call.
*
* The handler will be called on topic updates. It will be passed
* the new value of the topic as the first argument, and the name of
* the topic as the second argument.
*/
function subscribe(topic, handler, def) {

@@ -183,2 +225,9 @@ const subscription = {

/**
* Get the current value of a topic.
* @param {string} topic - The topic to get the value of.
* @param {*} default - (Optional) a value to return if the topic is
* empty.
* @returns {*} - The current value or the default
*/
function currentVal(topic, def) {

@@ -188,2 +237,8 @@ return valueOrDefault(store[topic], def);

/**
* Clears a given topic.
* @param {string} topic - The topic to clear
*
* Clears the topic by publishing a `null` to it.
*/
function clear(topic) {

@@ -195,2 +250,5 @@ if (store.hasOwnProperty(topic)) {

/**
* Clears all known topics.
*/
function clearAll() {

@@ -197,0 +255,0 @@ Object.keys(store).forEach(clear);

@@ -123,3 +123,3 @@ const clearRequire = require('clear-require');

// expect(handler).to.have.been.calledWith(testPayload, TEST_TOPIC_1);
expect(handler).to.have.been.calledWith(testPayload, TEST_TOPIC_1);
});

@@ -126,0 +126,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc