Skip to content

Instantly share code, notes, and snippets.

@veryphatic
Created June 13, 2015 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veryphatic/223119951f6520ab4a21 to your computer and use it in GitHub Desktop.
Save veryphatic/223119951f6520ab4a21 to your computer and use it in GitHub Desktop.
jQuery pubsub
// Subsriber and publisher pattern via https://api.jquery.com/jQuery.Callbacks/
var topics = {};
jQuery.Topic = function( id ) {
var callbacks, method,
topic = id && topics[ id ];
if ( !topic ) {
callbacks = jQuery.Callbacks();
topic = {
publish: callbacks.fire,
subscribe: callbacks.add,
unsubscribe: callbacks.remove
};
if ( id ) {
topics[ id ] = topic;
}
}
return topic;
};
// To subscribe to a topic
jQuery.Topic("topicName").subscribe(callback);
// To publish to a topic
jQuery.Topic("topicName").publish(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment