Created
June 13, 2015 02:19
-
-
Save veryphatic/223119951f6520ab4a21 to your computer and use it in GitHub Desktop.
jQuery pubsub
This file contains hidden or 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
// 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