Skip to content

Instantly share code, notes, and snippets.

@kalisjoshua
Forked from bentruyman/jquery-pubsub.js
Created January 8, 2012 03:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalisjoshua/1576989 to your computer and use it in GitHub Desktop.
Save kalisjoshua/1576989 to your computer and use it in GitHub Desktop.
Simple Pub/Sub Implementation for jQuery
/*
jQuery pub/sub plugin by Peter Higgins (dante@dojotoolkit.org)
Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
http://dojofoundation.org/license for more information.
*/
(function($) {
var topics = {};
$.publish = function (topic, args) {
if (topics[topic]) {
var current = topics[topic]
,i = 0
,l = current.length;
for (; i < l; i++) {
current[i].call($, args);
}
}
};
$.subscribe = function (topic, callback) {
(topics[topic] = topics[topic] || [])
.push(callback);
return {
"topic": topic
,"callback": callback
};
};
$.unsubscribe = function (handle) {
var current
,i = 0
,len
,topic = handle.topic;
if (topics[topic]) {
current = topics[topic];
for (len = current.length; i < len; i++) {
if (current[i] === handle.callback) {
current.splice(i, 1);
}
}
}
};
})(jQuery);
/*
jQuery pub/sub plugin by Peter Higgins (dante@dojotoolkit.org)
Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
http://dojofoundation.org/license for more information.
*/
(function(a){var b={};a.publish=function(c,d){if(b[c]){var e=b[c],f=0,g=e.length;for(;f<g;f++){e[f].call(a,d)}}};a.subscribe=function(a,c){(b[a]=b[a]||[]).push(c);return{topic:a,callback:c}};a.unsubscribe=function(a){var c,d=0,e,f=a.topic;if(b[f]){c=b[f];for(e=c.length;d<e;d++){if(c[d]===a.callback){c.splice(d,1)}}}}})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment