Skip to content

Instantly share code, notes, and snippets.

@Williammer
Last active July 8, 2018 09:09
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 Williammer/04e18e60d18ac9f0dc37 to your computer and use it in GitHub Desktop.
Save Williammer/04e18e60d18ac9f0dc37 to your computer and use it in GitHub Desktop.
jsPattern.PubSubImpl - one compact library-agnostic implementation by addyosmani. Purely for learning purpose.
/*!
* Pub/Sub implementation
* http://addyosmani.com/
* Licensed under the GPL
* http://jsfiddle.net/LxPrq/
*/
;(function ( window, doc, undef ) {
var topics = {},
subUid = -1,
pubsubz ={};
pubsubz.publish = function ( topic, args ) {
if (!topics[topic]) {
return false;
}
setTimeout(function () {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
};
pubsubz.subscribe = function ( topic, func ) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
pubsubz.unsubscribe = function ( token ) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
getPubSubz = function(){
return pubsubz;
};
window.pubsubz = getPubSubz();
}( this, this.document ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment