Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { DEFAULT_ADAPTER } from './constants';
- /*
- Remove a token from an array of subscriptions
- @param subscriptions Array (of tokens)
- @param token Array ([action, callback])
- */
- const removeSubscription = (subscriptions, token, adapter) => {
- const idx = subscriptions.indexOf(token);
- if (idx < 0) {
- console.log('PubSub cannot unregister an unrecognized token');
- } else {
- subscriptions.splice(idx, 1);
- adapter.unsubscribe(token);
- }
- };
- /*
- Creates the subscription object
- @param component function the React component
- @param autoUnmount boolean defaults to true, if it has to remove all subscriptions on cwunmount
- @param adapter object the pubsub adapter
- @return the subscription object
- */
- const createSubscription = function(component, autoUnmount = true, adapter) {
- let sub = {
- componentWillUnmount: component.componentWillUnmount,
- subscriptions: [],
- add(action, cb) {
- const token = adapter.subscribe(action, cb);
- sub.subscriptions.push(token);
- return () => removeSubscription(sub.subscriptions, token);
- },
- removeAll() {
- sub.subscriptions.forEach( token => adapter.unsubscribe(token) );
- sub.subscriptions = [];
- },
- publish(action, params) {
- adapter.publish(action, params);
- }
- };
- if (autoUnmount) {
- component.componentWillUnmount = () => {
- const { componentWillUnmount, removeAll } = sub;
- componentWillUnmount && componentWillUnmount.apply(component, arguments);
- removeAll();
- sub = void 0;
- };
- }
- return sub;
- };
- /*
- PubSubAdapter function
- @param Object adapter being used
- @returns an object wrapping publish/subscribe/unsubscribe from given adapter
- */
- const PubSubAdapter = (adapter) => {
- const { publish, subscribe, unsubscribe } = adapter;
- return {
- publish,
- subsribe,
- unsubscribe
- }
- };
- /*
- createPubSub function
- @param subscribersMap Object, default to empty object, subscribers that will be populated
- like so:
- subscribersMap[MyReactComponent] = {...}
- @param adapter Object, default to default adapter specified
- @returns an object wrapping register/unregister for a particular component
- */
- const createPubSub = (subscribersMap = {}, adapter = DEFAULT_ADAPTER) => {
- return {
- register(component, autoUnmount = true) {
- let registeredComponent = subscribersMap[component];
- registeredComponent = registeredComponent || createSubscription(component, autoUnmount, PubSubAdapter(adapter));
- return registeredComponent;
- },
- unregister(component) {
- if (subscribersMap[component]) {
- subscribersMap[component].removeAll() && delete subscribersMap[component];
- } else {
- console.log(`${component.displayName} is NOT registerd to PubSub`);
- }
- },
- };
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement