Created
August 16, 2013 00:13
-
-
Save mattgoucher/6246141 to your computer and use it in GitHub Desktop.
Publish and Subscribe
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
(function() { | |
/** | |
* Make sending and recieving messages easy. | |
*/ | |
function PubSub() { | |
// Dictionary of events | |
this.events = {}; | |
} | |
/** | |
* Add a subscriber | |
* @param {string} name what do subscribe to | |
* @param {function} sub what gets fired when triggered | |
* @return {undefined} | |
*/ | |
PubSub.prototype.on = function(name, sub) { | |
if (this.events[name]) { | |
// Already has subscribers | |
this.events[name].push(sub); | |
}else{ | |
// No subscribers | |
this.events[name] = [sub]; | |
} | |
}; | |
/** | |
* Remove subscriptions for an event name | |
* @param {string} name Name of event to remove subscriptions from | |
* @return {undefined} | |
*/ | |
PubSub.prototype.off = function(name) { | |
if (this.events[name]) { | |
for (var i = 0; i < this.events[name]; i++) { | |
// Null subscriptions out | |
this.events[name][i] = null; | |
} | |
// Blow away the event | |
delete this.events[name]; | |
} | |
}; | |
/** | |
* Publish to a subscription | |
* @param {string} name what event gets triggered | |
* @param {value} value what do we pass to the event | |
* @return {array} the result of each subscriber called | |
*/ | |
PubSub.prototype.trigger = function(name, value) { | |
var results = []; | |
// Ensure we have a subscriber for this key | |
if (!this.events[name]) { | |
return; // No subscribers | |
} | |
for (var i = 0; i < this.events[name].length; i++) { | |
var subscriber = this.events[name][i]; | |
// Call the subscriber, passing the value | |
if (typeof subscriber === "function") { | |
results.push(subscriber(value)); | |
} | |
} | |
return results; | |
}; | |
window.PubSub = new PubSub(); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment