Created
November 4, 2016 18:22
-
-
Save pgarciacamou/d719b3fd39eeb9758963d8c0f979ce00 to your computer and use it in GitHub Desktop.
Publish Subscribe JS Pattern mini module.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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)); | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).