Created
July 7, 2014 14:43
-
-
Save barmatz/7027c489bc4d77e4b0ff to your computer and use it in GitHub Desktop.
A subscribe/publish event manager class
This file contains hidden or 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
| 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