Created
October 24, 2019 12:04
-
-
Save VictorZhang2014/1924e83feb190eb0804df3474b68e3d2 to your computer and use it in GitHub Desktop.
The simplest notification, Subscribe/Publish in Javascript
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
// Notification Messages | |
// This is made by Publish-Subscribe Topics | |
class YLNotificationMessages { | |
constructor () { | |
// Event Objects: storing event name and event callback | |
this.events = {}; | |
} | |
// Subscribe Event | |
subscribe (eventName, callback) { | |
if (!this.events[eventName]) { | |
// One event name can be used for multiple event callbacks | |
this.events[eventName] = [callback]; | |
} else { | |
// If the event name exists, then add more callbacks to it | |
this.events[eventName].push(callback); | |
} | |
} | |
// Publish Event with arguments | |
publish (eventName, ...args) { | |
this.events[eventName] && this.events[eventName].forEach(cb => cb(...args)); | |
} | |
// Unsubscribe Event by name and callback | |
unsubscribe (eventName, callback) { | |
if (this.events[eventName]) { | |
// Find the callback in accordance with its event name and remove it from the event list. | |
this.events[eventName].filter(cb => cb != callback); | |
} | |
} | |
} | |
// Register the class to Window Objects in Javascript | |
window["YLNotificationMessages"] = new YLNotificationMessages(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is how we subscribe the event
When we publish data and all the subscribers will receive the data