Created
October 17, 2012 19:38
-
-
Save aaronmccall/3907650 to your computer and use it in GitHub Desktop.
tiny standalone pubsub in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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