const pubsub = {};
(function(myObject) {
const topics = {};
let subUid = -1;
myObject.publish = function(topic, args) {
if(!topics[topic]) {
return false
}
const subscribers = topics[topic];
let len = subscribers ? subscribers.length : 0
while(len--) {
subscribers[len].func(topic, args)
}
return this;
}
myObject.subscribe = function(topic, func) {
if(!topics[topic]) {
topics[topic] = []
}
const token = (++subUid).toString()
topics[topic].push({
token,
func
})
return token
}
myObject.unsubscribe = function(token) {
for(var m in topics) {
if(topics[m]) {
for(var i = 0, j = topics[m].length; i < j; i++) {
if(topics[m][i].token === token) {
topics[m].splice(i, 1)
return token
}
}
}
}
return this
}
}(pubsub));
const getCurrentTime = function() {
const date = new Date(),
m = date.getMonth() + 1,
d = date.getDate(),
y = date.getFullYear(),
t = date.toLocaleTimeString().toLowerCase()
return (`${m}/${d}/${y} ${t}`)
}
function addGridRow(data) {
console.log(`update grid component with: ${data}`)
}
function updateCounter(data) {
console.log(`data last updated at: ${getCurrentTime()} with ${data}`)
}
const gridUpdate = function(topic, data) {
console.log(89898989)
if(data !== undefined) {
addGridRow(data)
updateCounter(data)
}
}
const gridUpdate1 = function(topic, data) {
console.log(121212121)
if(data !== undefined) {
addGridRow(data)
updateCounter(data)
}
}
const subscriber = pubsub.subscribe('newDataAvailable', gridUpdate)
const subscriber1 = pubsub.subscribe('newDataAvailable', gridUpdate1)
pubsub.unsubscribe(subscriber1)
pubsub.publish('newDataAvailable', {
summary: 'Apple made $5 billion',
identifier: 'APPL',
stockPrice: 570.91
})
pubsub.publish('newDataAvailable', {
summary: 'Microsoft made $20 million',
identifier: 'MSFT',
stockPrice: 30.85
})
/*
var messageLogger = function(topics, data) {
console.log(`Logging: ${topics} : ${data}`)
}
var subscription = pubsub.subscribe('inbox/newMessage', messageLogger)
pubsub.publish('inbox/newMessage', 'hello world')
pubsub.publish('inbox/newMessage', ['test', 'a', 'b', 'c'])
pubsub.publish('inbox/newMessage', {
sender: 'hello@google.com',
body: 'Hey again!'
})
pubsub.unsubscribe(subscription)
pubsub.publish('inbox/newMessage', 'Hello! are you still there?')
*/
console