This seems to work, but for some reason I'm not entirely sure about it.
Can anyone point out any issues with this simple pub/sub library? Thank you!
(function (undefined) {
window.mylib = $.extend(window.mylib, (function () {
var subscriptionsBag = function() {
var self = this;
self.count = -1;
self.handlers = {};
var cancel = function(index) {
var self = this;
delete self.handlers[index];
};
self.add = function (fn) {
if (typeof(fn) !== "function") {
throw new Error("function expected.");
}
var index = ++self.count;
self.handlers[self.count] = fn;
return {
cancel: cancel.bind(self, index)
};
};
self.fire = function(obj) {
for (var handlerKey in self.handlers) {
if (!self.handlers.hasOwnProperty(handlerKey)) {
continue;
}
var handler = self.handlers[handlerKey];
if (!handler) continue;
handler(obj);
}
};
};
var subscriptions = {
"": {}
};
var publish = function(e, obj) {
var evt = "@" + e;
var subs = subscriptions[evt];
if (!subs) return;
subs.fire(obj);
};
var subscribeTo = function (e, fn) {
var evt = "@" + e;
var subs = subscriptions[evt] = (subscriptions[evt] || new subscriptionsBag());
return subs.add(fn);
};
var events = {
publish: publish,
subscribeTo: subscribeTo
};
return {
events: events
};
})());
})();