-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I asked ChatGPT to write the same kind of library and it gave me this.