Skip to content

Instantly share code, notes, and snippets.

@ichpuchtli
Created November 21, 2015 09:22
Show Gist options
  • Save ichpuchtli/57dfd220faebbb92c5dd to your computer and use it in GitHub Desktop.
Save ichpuchtli/57dfd220faebbb92c5dd to your computer and use it in GitHub Desktop.
A super dumb pub sub implementation
export interface PubSubCallback
{
(args?: any, topic?: any) : void;
}
interface PubSubTopicMap
{
[topic : string]: PubSubCallback[];
}
class DumbPubSubStub
{
public static debugging: boolean = true;
private static map : PubSubTopicMap = {};
public static Publish(topic: any, args?: any)
{
if (DumbPubSubStub.debugging)
{
console.info(`publish: ${topic} -> `, args);
}
if (DumbPubSubStub.map[topic])
{
DumbPubSubStub.map[topic].forEach(callback => callback(args || {}, topic));
}
}
public static Unsubscribe(topic: any, func: PubSubCallback): void
{
if (DumbPubSubStub.debugging)
{
console.info(`unsubscribe: ${topic}`);
console.trace();
}
DumbPubSubStub.map[topic].splice(DumbPubSubStub.map[topic].indexOf(func), 1);
}
public static Subscribe(topic: any, callback: PubSubCallback)
{
if (DumbPubSubStub.debugging)
{
console.info(`subscribe: ${topic}`);
console.trace();
}
DumbPubSubStub.map[topic] = DumbPubSubStub.map[topic] || [];
DumbPubSubStub.map[topic].push(callback);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment