Skip to content

Instantly share code, notes, and snippets.

@wing-puah
Created March 14, 2020 15:23
Show Gist options
  • Select an option

  • Save wing-puah/364f377c1275b96a8b29a8972eaa03bb to your computer and use it in GitHub Desktop.

Select an option

Save wing-puah/364f377c1275b96a8b29a8972eaa03bb to your computer and use it in GitHub Desktop.
Pub-sub code gist example
class Cat {
constructor(name, interests) {
this.name = name;
this.interests = interests;
this.unsubscribe = {};
}
addUnsubscription(keyName, method) {
this.unsubscribe[keyName] = method;
}
}
const { PubSub } = require('./PubSub');
const { Cat } = require('./Cat');
const catDomPubSub = new PubSub();
const cat1 = new Cat('Midnight', ['climb trees', 'hunt', 'weather']);
const cat2 = new Cat('Bear', ['humour', 'weather', 'camera skills']);
const cat3 = new Cat('Smokey', ['hunt', 'camera skills']);
const allCat = [cat1, cat2, cat3];
allCat.forEach((singleCat, idx) => {
const { name, interests } = singleCat;
interests.forEach(interest => {
const { unsubscribe } = catDomPubSub.subscribe(interest, data =>
printInterestReceived(name, interest, data),
);
allCat[idx].addUnsubscription(interest, unsubscribe);
});
});
function printInterestReceived(name, interest, data) {
console.log(`${name} has received information for ${interest}: ${data}`);
}
catDomPubSub.publish('climb trees', 'Learn coordination');
catDomPubSub.publish('weather', 'Might rain tomorrow, stay indoors!');
catDomPubSub.publish(
'hunt',
'Predicted migration of house rats tomorrow, stay alert',
);
cat1.unsubscribe.hunt();
catDomPubSub.publish(
'hunt',
'Predicted migration of house rats tomorrow, stay alert',
);
class PubSub {
constructor() {
this.subscribers = {};
}
subscribe(event, callback) {
if (!this.subscribers[event]) {
this.subscribers[event] = [];
}
const index = this.subscribers[event].push(callback) - 1;
const { subscribers } = this;
return {
unsubscribe: function() {
subscribers[event].splice(index, 1);
},
};
}
publish(event, data) {
if (!this.subscribers[event]) {
return;
}
this.subscribers[event].forEach(subscriberCallback =>
subscriberCallback(data),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment