Skip to content

Instantly share code, notes, and snippets.

@AhmedTarekHasan
Last active October 19, 2021 13:01
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 AhmedTarekHasan/173b55c5d749bea47f7d1637fc4feda6 to your computer and use it in GitHub Desktop.
Save AhmedTarekHasan/173b55c5d749bea47f7d1637fc4feda6 to your computer and use it in GitHub Desktop.
let Subject = function(subscribersStateChangeNotificationCallback) {
let self = this;
let handlers = {};
Object.defineProperty(self, "subscribersFound", {
get() {
let found = false;
for(const prop in handlers) {
if(handlers.hasOwnProperty(prop)) {
found = true;
break;
}
}
return found;
}
});
Object.defineProperty(self, "subscribersCount", {
get() {
let count = 0;
for(const prop in handlers) {
if(handlers.hasOwnProperty(prop)) {
count++;
}
}
return count;
}
});
let unsubscribeNotificationCallback = (handlerId) => {
if(handlerId && handlerId !== '' && handlers.hasOwnProperty(handlerId)) {
delete handlers[handlerId];
if(subscribersStateChangeNotificationCallback && !self.subscribersFound) {
subscribersStateChangeNotificationCallback(false);
}
}
};
self.subscribe = (handler) => {
let handlerId = createGuid();
handlers[handlerId] = handler;
if(subscribersStateChangeNotificationCallback && self.subscribersCount === 1) {
subscribersStateChangeNotificationCallback(true);
}
return new Subscription(handlerId, unsubscribeNotificationCallback);
};
self.next = (data) => {
for(const handlerId in handlers) {
handlers[handlerId](data);
}
};
return self;
};
let createGuid = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment