Skip to content

Instantly share code, notes, and snippets.

@jessycormier
Last active January 23, 2016 23:09
Show Gist options
  • Save jessycormier/e347017b6a389ae96aae to your computer and use it in GitHub Desktop.
Save jessycormier/e347017b6a389ae96aae to your computer and use it in GitHub Desktop.
Simple pub/sub script.

#Basic Pub / Sub Based off of this gist by learncodeacademy.

The min.js version removes ViewLedger funciton.

var emitter = (function() {
"use strict";
//VARS
var _name = 'Emitter';
var ledger = {}; // Stores the subscribed callbacks to be triggered on event emit.
//GETTERS
// Return a view of the ledger / mostly for fun
function viewLedger() {
var l = ledger;
return l;
}
// FUNCTIONS
// subscribe to an event
function subscribe(eventName, fn) {
console.debug('%s [ subscribe ] : ( %s )', _name, eventName);
// Creates an empty array on the ledger object if one doesn't exist already
ledger[eventName] = ledger[eventName] || [];
// Add the function to be called when this event is emitted
ledger[eventName].push(fn);
}
// unsubscribe an event
function unsubscribe(eventName, fn) {
console.debug('%s [ unsubscribe ] : ( %s )', _name, eventName);
if (ledger[eventName]) {
for (var i = 0; i < ledger[eventName].length; i++) {
if (ledger[eventName][i] === fn) {
ledger[eventName].splice(i, 1);
break;
}
}
}
}
// Emit event(s)
function emit(eventName, data) {
console.debug('%s [ emit ] : ( %s )', _name, eventName);
if (ledger[eventName]) {
console.debug('\tFound( %s ) %s to emit.', ledger[eventName].length, eventName);
ledger[eventName].forEach(function (fn) {
fn(data); // call the fn of each "subscribed" event
console.debug('\t\t callback ran:', fn.toString().split(' ')[1]);
});
}
else {
console.debug('\t No Subscribers');
}
}
//EXPOSE
return {
ViewLedger: viewLedger,
Subscribe: subscribe,
Unsubscribe: unsubscribe,
Emit: emit
};
})();
var emitter=function(){"use strict";function i(i,n){t[i]=t[i]||[],t[i].push(n)}function n(i,n){if(t[i])for(var r=0;r<t[i].length;r++)if(t[i][r]===n){t[i].splice(r,1);break}}function r(i,n){t[i]&&t[i].forEach(function(i){i(n)})}var t={};return{Subscribe:i,Unsubscribe:n,Emit:r}}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment