Skip to content

Instantly share code, notes, and snippets.

@mnishihan
Created October 25, 2012 22:50
Show Gist options
  • Save mnishihan/3955963 to your computer and use it in GitHub Desktop.
Save mnishihan/3955963 to your computer and use it in GitHub Desktop.
JavaScript: Library Agnostic Pub/Sub
App = {};
App.cache = {};
App.publish = function(topic, args){
App.cache[topic] && $.each(App.cache[topic], function(){
this.apply($, args || []);
});
};
App.subscribe = function(topic, callback){
if(!App.cache[topic]){
App.cache[topic] = [];
}
App.cache[topic].push(callback);
return [topic, callback];
};
App.unsubscribe = function(handle){
var t = handle[0];
App.cache[t] && $.each(App.cache[t], function(idx){
if(this == handle[1]){
App.cache[t].splice(idx, 1);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment