-
-
Save JBreit/6e262c60d88db2ba301b to your computer and use it in GitHub Desktop.
Simple Pub/Sub Implementation for jQuery
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
/* | |
* Simple Pub/Sub Implementation for jQuery | |
* | |
* Inspired by work from Peter Higgins (https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js) | |
* | |
* This is about the simplest way to write a pubsub JavaScript implementation for use with jQuery. | |
*/ | |
(function( $ ) { | |
// Cache of all topics | |
var topics = {}; | |
// Iterates through all subscribers of a topic and invokes their callback, | |
// passing optional arguments. | |
$.publish = function( topic, args ) { | |
if ( topics[ topic ] ) { | |
var thisTopic = topics[ topic ], | |
thisArgs = args || []; | |
for ( var i = 0, j = thisTopic.length; i < j; i++ ) { | |
thisTopic[i].apply( $, thisArgs ); | |
} | |
} | |
}; | |
// Returns a handle needed for unsubscribing | |
$.subscribe = function( topic, callback ) { | |
if ( !topics[ topic ] ) { | |
topics[ topic ] = []; | |
} | |
topics[ topic ].push( callback ); | |
return { | |
topic: topic, | |
callback: callback | |
}; | |
}; | |
// Removes the subscriber from the particular topic its handle was assigned to | |
$.unsubscribe = function( handle ) { | |
var topic = handle.topic; | |
if ( topics[ topic ] ) { | |
var thisTopic = topics[ topic ]; | |
for ( var i = 0, j = thisTopic.length; i < j; i++ ) { | |
if ( thisTopic[i] === handle.callback ) { | |
thisTopic.splice( i, 1 ); | |
// break; here? duplicate handles are possible | |
} | |
} | |
} | |
}; | |
})( jQuery ); | |
/* | |
For example: | |
var handle = $.subscribe('notification', function (msg) { | |
alert(msg); | |
}); | |
$.publish('notification', ['Hello World']); | |
$.unsubscribe(handle); | |
*/ |
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
/* | |
* Simple Pub/Sub Implementation for jQuery | |
* | |
* Inspired by work from Peter Higgins (https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js) | |
* | |
* This is about the simplest way to write a pubsub JavaScript implementation for use with jQuery. | |
*/ | |
(function(a){var b={};a.publish=function(c,d){if(b[c]){var e=b[c],f=d||[];for(var g=0,h=e.length;g<h;g++)e[g].apply(a,f)}},a.subscribe=function(a,c){b[a]||(b[a]=[]),b[a].push(c);return{topic:a,callback:c}},a.unsubscribe=function(a){var c=a.topic;if(b[c]){var d=b[c];for(var e=0,f=d.length;e<f;e++)d[e]===a.callback&&d.splice(e,1)}}})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment