Skip to content

Instantly share code, notes, and snippets.

@aaronmccall
Created October 17, 2012 19:38
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 aaronmccall/3907650 to your computer and use it in GitHub Desktop.
Save aaronmccall/3907650 to your computer and use it in GitHub Desktop.
tiny standalone pubsub in javascript
//PubSub
(function(attachTo, defaultContext) {
var topics = {},
attachTo = attachTo||this,
defaultContext = defaultContext||this,
__slice = function (obj) { return [].prototype.slice.call(obj) };
attachTo.publish = function() {
var args = __slice(arguments),
topic = args.shift();
if (topics[topic]) {
var currentTopic = topics[topic]||[];
for (var i = 0, j = currentTopic.length; i < j; i++) {
currentTopic[i].apply(null, args || []);
}
}
};
attachTo.subscribe = function(topic, callback, context) {
var cb = callback.bind
? callback.bind(context||defaultContext)
: function () {
callback.apply(context||defaultContext, Array.prototype.slice.call(arguments));
};
if (!topics[topic]) topics[topic] = [];
topics[topic].push(cb);
return { "topic": topic, "callback": cb };
};
attachTo.unsubscribe = function(handle) {
var topic = handle.topic;
if (topics[topic]) {
var currentTopic = topics[topic];
for (var i = 0, j = currentTopic.length; i < j; i++) {
if (currentTopic[i].callback === handle.callback) {
currentTopic.splice(i, 1);
}
}
}
};
})(my_container||window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment