Skip to content

Instantly share code, notes, and snippets.

@Kcko
Created February 6, 2019 08:48
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 Kcko/902102eafda8f6107cf6a79b78963909 to your computer and use it in GitHub Desktop.
Save Kcko/902102eafda8f6107cf6a79b78963909 to your computer and use it in GitHub Desktop.
;(function(d){
// the topic/subscription hash
var cache = {};
d.publish = function(/* String */topic, /* Array? */args){
// summary:
// Publish some data on a named topic.
// 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.
//
// example:
// Publish stuff on '/some/topic'. Anything subscribed will be called
// with a function signature like: function(a,b,c){ ... }
//
// | $.publish("/some/topic", ["a","b","c"]);
cache[topic] && d.each(cache[topic], function(){
this.apply(d, args || []);
});
};
d.subscribe = function(/* String */topic, /* Function */callback){
// summary:
// Register a callback on a named topic.
// 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.
//
// example:
// | $.subscribe("/some/topic", function(a, b, c){ /* handle data */ });
//
if(!cache[topic]){
cache[topic] = [];
}
cache[topic].push(callback);
return [topic, callback]; // Array
};
d.unsubscribe = function(/* Array */handle){
// summary:
// Disconnect a subscribed function for a topic.
// handle: Array
// The return value from a $.subscribe call.
// example:
// | var handle = $.subscribe("/something", function(){});
// | $.unsubscribe(handle);
var t = handle[0];
cache[t] && d.each(cache[t], function(idx){
if(this == handle[1]){
cache[t].splice(idx, 1);
}
});
};
})(jQuery);
$.subscribe("test", function(a,b) {
console.log(arguments);
});
$('button').on('click', function(e){
$.publish("test", [e, "a","b"]);
});
/*
OUTPUT:
Arguments(3) [j…y.Event, "a", "b", callee: ƒ, Symbol(Symbol.iterator): ƒ]0: jQuery.Event {originalEvent: MouseEvent, type: "click", isDefaultPrevented: ƒ, timeStamp: 2187.000000005355, jQuery112409936550241987452: true, …}1: "a"2: "b"callee: ƒ (a,b)length: 3Symbol(Symbol.iterator): ƒ values()__proto__: Object
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment