Skip to content

Instantly share code, notes, and snippets.

@pgarciacamou
Created November 4, 2016 18:22
Show Gist options
  • Save pgarciacamou/d719b3fd39eeb9758963d8c0f979ce00 to your computer and use it in GitHub Desktop.
Save pgarciacamou/d719b3fd39eeb9758963d8c0f979ce00 to your computer and use it in GitHub Desktop.
Publish Subscribe JS Pattern mini module.
/**
* Simple implementation of Publish and Subscribe Pattern
*
* This helps a lot specially when the components are
* not close enough that passing a function as props
* looks ugly.
*/
const topics = {};
module.exports = {
subscribe: function (topic, callback) {
topics[topic] = topics[topic] || [];
topics[topic].push(callback);
},
publish: function (topic, data) {
topics[topic] = topics[topic] || [];
topics[topic].forEach(cb => {
cb(Object.create(data));
});
}
};
@pgarciacamou
Copy link
Author

I created this for readability in a React App (as a mixin, we could communicate different React Components). BUT it is very un-react-y (bad practice).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment