Skip to content

Instantly share code, notes, and snippets.

@VictorZhang2014
Created October 24, 2019 12:04
Show Gist options
  • Save VictorZhang2014/1924e83feb190eb0804df3474b68e3d2 to your computer and use it in GitHub Desktop.
Save VictorZhang2014/1924e83feb190eb0804df3474b68e3d2 to your computer and use it in GitHub Desktop.
The simplest notification, Subscribe/Publish in Javascript
// 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();
@VictorZhang2014
Copy link
Author

VictorZhang2014 commented Oct 24, 2019

This is how we subscribe the event

window.YLNotificationMessages.subscribe("ReceiveMessages", function(data) {
     console.log(data);
});

When we publish data and all the subscribers will receive the data

var data = {
     "user_id": 28648,
     "user_name": "jd",
     "user_language": "en",
     "user_uuid": "8b3d1204-e2ee-11e9-9d7c-1f8e47066aae",
     "user_email": "123456@gmail.com",
     "user_avatar": "https://google.com/icon.png"
};
window.YLNotificationMessages.publish("ReceiveMessages", data);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment