Skip to content

Instantly share code, notes, and snippets.

@barmatz
Created July 7, 2014 14:43
Show Gist options
  • Select an option

  • Save barmatz/7027c489bc4d77e4b0ff to your computer and use it in GitHub Desktop.

Select an option

Save barmatz/7027c489bc4d77e4b0ff to your computer and use it in GitHub Desktop.
A subscribe/publish event manager class
window.EventSubPubManager = window.EventSubPubManager || (function() {
function EventSubPubManager() {
this.__ = {}
}
EventSubPubManager.prototype.subscribe = function(topic, callback) {
var callbacks = this.__[topic];
if (!callbacks) {
callbacks = this.__[topic] = [];
}
callbacks.push(callback);
};
EventSubPubManager.prototype.unsubscribe = function(topic, callback) {
var callbacks = this.__[topic];
if (callbacks) {
callbacks.splice($(callbacks).index(callback), 1);
if (callbacks.length === 0) {
this.__[topic] = null;
delete this.__[topic];
}
}
};
EventSubPubManager.prototype.publish = function(topic /*...args*/ ) {
var callbacks = this.__[topic],
targetCallbacks = [],
args = Array.prototype.slice.call(arguments).splice(0, 1),
i;
if (callbacks) {
for (i = 0; i < callbacks.length; i += 1) {
targetCallbacks.push(callbacks[i]);
}
for (i = 0; i < targetCallbacks.length; i += 1) {
targetCallbacks[i].apply(window, args);
}
}
};
return EventSubPubManager;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment