Skip to content

Instantly share code, notes, and snippets.

@Made-of-Clay
Forked from fatihacet/pubsub-simple.js
Last active July 12, 2023 13:26
Show Gist options
  • Save Made-of-Clay/7161b6d251dc458725fa07b9901f5325 to your computer and use it in GitHub Desktop.
Save Made-of-Clay/7161b6d251dc458725fa07b9901f5325 to your computer and use it in GitHub Desktop.
Simple PubSub implementation with JavaScript - taken from Addy Osmani's design patterns book & ESM-ified
let topics = {}, subUid = -1;
// https://gist.github.com/fatihacet/1290216
export default {
subscribe(topic, func) {
if (!topics[topic]) {
topics[topic] = [];
}
let token = (++subUid).toString();
topics[topic].push({
token,
func
});
return token;
},
publish(topic, args) {
if (!topics[topic]) {
return false;
}
setTimeout(() => {
let subscribers = topics[topic];
let len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
},
unsubscribe(token) {
for (let m in topics) {
if (topics[m]) {
for (let i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
}
};
@Made-of-Clay
Copy link
Author

I asked ChatGPT to write the same kind of library and it gave me this.

const topics = {};

export function subscribe(topic, callback) {
  if (!topics[topic]) {
    topics[topic] = [];
  }
  topics[topic].push(callback);
}

export function publish(topic, data) {
  if (!topics[topic]) {
    return;
  }
  topics[topic].forEach(callback => {
    callback(data);
  });
}

export function unsubscribe(topic, callback) {
  if (!topics[topic]) {
    return;
  }
  const index = topics[topic].indexOf(callback);
  if (index !== -1) {
    topics[topic].splice(index, 1);
  }
}

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