Skip to content

Instantly share code, notes, and snippets.

@muralikrishnat
Created February 3, 2020 09:41
Show Gist options
  • Save muralikrishnat/9d9b71a1d45b9e97b0b99014ca752a3d to your computer and use it in GitHub Desktop.
Save muralikrishnat/9d9b71a1d45b9e97b0b99014ca752a3d to your computer and use it in GitHub Desktop.
Simple PubSub service file
import { pubSub } from '../../services/pubsub.service';
//subscribe the event for pageloader to listen the event
pubSub.subscribe('pageloader', (event) => {
if (event.show) {
this.setState({
isLoading: true
});
} else {
this.setState({
isLoading: false
});
}
});
//publish the event from another file or other soruce event
pubSub.publish('pageloader', {
show: false
});
let PubSub = function() {
this.pubSubHash = {};
};
PubSub.prototype.subscribe = function(eventName, eventFn) {
if (!this.pubSubHash[eventName]) {
this.pubSubHash[eventName] = [];
}
this.pubSubHash[eventName].push(eventFn);
};
PubSub.prototype.publish = function(eventName, eventData) {
if(this.pubSubHash[eventName]) {
this.pubSubHash[eventName].forEach(eventFn => {
eventFn(eventData);
});
}
};
export const pubSub = new PubSub();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment