Created
August 11, 2020 21:33
-
-
Save jucian0/b3776a4ebceaedf863089c82352eac4c to your computer and use it in GitHub Desktop.
This file contains 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
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