Skip to content

Commit

Permalink
add first version with basic usage
Browse files Browse the repository at this point in the history
  • Loading branch information
griffithtp committed May 10, 2020
1 parent da6ea3d commit 38b6f86
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,34 @@
localpubsub
===

Simple pubsub lightweight library using Window event listener and storage event.

#### Subscribing
`subscribe(topic, callbackFunction);`


```
import localpubsub from 'localpubsub';
function displayMessage(data) {
console.log(data)
}
localpubsub.subscribe('my topic', displayMessage);
```

#### Publishing
`publish(topic, message);`

```
localpubsub.publish('my topic', 'Hello');
```

#### Unsubscribe
`unsubscribe(topic);`

```
const subscription = localpubsub.subscribe(topic, displayMessage);
subscription.unsubscribe();
localpubsub.unsubscribe(topic);
```
54 changes: 54 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
let topics = {};

function subscribe(topic, listener) {
if (!topics.hasOwnProperty(topic)) {
topics[topic] = listener;
}
window.addEventListener(
topic,
eventData => processCustomEvent(topic, listener, eventData),
false
);
window.addEventListener(
"storage",
eventData => processStorage(topic, listener, eventData),
false
);
return {
unsubscribe: () => {
unsubscribe(topic);
}
};
}

function processCustomEvent(topic, cb, result) {
if (topic === result.type) {
return cb({ topic, value: result.detail, eventObject: result });
}
}

function processStorage(topic, cb, result) {
if (topic === result.key) {
return cb({ topic, value: result.newValue, eventObject: result });
}
}

function publish(eventName, eventValue) {
if (topics[eventName]) {
window.localStorage.setItem(eventName, eventValue);
const customEvent = new CustomEvent(eventName, { detail: eventValue });
window.dispatchEvent(customEvent);
}
}

function unsubscribe(subscribeKey) {
window.localStorage.removeItem(subscribeKey);
delete topics[subscribeKey];
}

export default {
topics,
publish,
subscribe,
unsubscribe
};

0 comments on commit 38b6f86

Please sign in to comment.