-
-
Save kalisjoshua/1576989 to your computer and use it in GitHub Desktop.
Simple Pub/Sub Implementation for jQuery
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
/* | |
jQuery pub/sub plugin by Peter Higgins ([email protected]) | |
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); |
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
/* | |
jQuery pub/sub plugin by Peter Higgins ([email protected]) | |
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