Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
76 lines (62 sloc) 2.37 KB
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
/* Title: One of the many third-party plugins
* Description: Peter Higgin's jQuery plugin, available here: https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js
*/
;(function(d){
// the topic/subscription hash
var cache = {};
// Publish some data on a named topic.
d.publish = function(/* String */topic, /* Array? */args){
// topic: String - The channel to publish on
// args: Array - The data to publish. Each array item is converted into an ordered
// arguments on the subscribed functions.
cache[topic] && d.each(cache[topic], function(){
this.apply(d, args || []);
});
};
// Register a callback on a named topic.
d.subscribe = function(/* String */topic, /* Function */callback){
// @topic: String - The channel to subscribe to
// @callback: Function - The handler event. Anytime something is $.publish'ed on a
// subscribed channel, the callback will be called with the published array as
// ordered arguments.
//
// returns: Array - A handle which can be used to unsubscribe this
// particular subscription.
if(!cache[topic]){
cache[topic] = [];
}
cache[topic].push(callback);
return [topic, callback]; // Array
};
// Disconnect a subscribed function for a topic.
d.unsubscribe = function(/* Array */handle){
// handle: Array - The return value from a $.subscribe call.
var t = handle[0];
cache[t] && d.each(cache[t], function(idx){
if(this == handle[1]){
cache[t].splice(idx, 1);
}
});
};
})(jQuery);
// Usage:
// Publish stuff on '/some/topic'. Anything subscribed will be called
// with a function signature like: function(a,b,c){ ... }
$.subscribe("/some/topic", function(a, b, c){
console.log(a,b,c);
});
$.publish("/some/topic", ["a","b","c"]);
// References
// https://gist.github.com/1321768
</script>
</body>
</html>