Skip to content

Instantly share code, notes, and snippets.

@jucian0
Created August 11, 2020 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jucian0/b3776a4ebceaedf863089c82352eac4c to your computer and use it in GitHub Desktop.
Save jucian0/b3776a4ebceaedf863089c82352eac4c to your computer and use it in GitHub Desktop.
class PubSub {
constructor() {
this.subscribers = {};
}
subscribe(event, fn) {
if (Array.isArray(this.subscribers[event])) {
this.subscribers[event] = [...this.subscribers[event], fn];
} else {
this.subscribers[event] = [fn];
}
return () => {
this.unsubscribe(event, fn);
};
}
unsubscribe(event, fn) {
this.subscribers[event] = this.subscribers[event].filter(
(sub) => sub !== fn
);
}
publish(event, data) {
if (Array.isArray(this.subscribers[event])) {
this.subscribers[event].forEach((sub) => {
sub(data);
});
}
return false;
}
}
export default new PubSub();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment