Skip to content

Instantly share code, notes, and snippets.

@SeanJM
Created March 14, 2016 15:16
Show Gist options
  • Select an option

  • Save SeanJM/8f2773c41c52551ff1ca to your computer and use it in GitHub Desktop.

Select an option

Save SeanJM/8f2773c41c52551ff1ca to your computer and use it in GitHub Desktop.
function createSubscriber() {
'use strict';
var subscriber = {};
var f = {};
if (typeof f !== 'object') {
throw 'The argument for \'createSubscriber\' must be type object';
}
f.on = function (name, fn) {
var i, n, x;
var names = name.split(',');
for (i = 0, n = names.length; i < n; i++) {
x = names[i].trim();
if (typeof subscriber[x] === 'undefined') {
subscriber[x] = [];
}
if (subscriber[x].indexOf(fn) === -1) {
subscriber[x].push(fn);
}
}
};
f.off = function (name, fn) {
var index, n, i, x;
var names = name.split(',');
for (i = 0, n = names.length; i < n; i++) {
x = names[i].trim();
if (typeof subscriber[x] === 'undefined') {
throw 'There are no subscribers for \'' + x + '\'';
}
index = subscriber[x].indexOf(fn);
if (index !== -1) {
subscriber[x].slice(index, 1);
}
}
};
f.trigger = function (name, e) {
var index, n, i, x, j, k;
var names = name.split(',');
for (i = 0, n = names.length; i < n; i++) {
x = names[i].trim();
if (typeof subscriber[x] === 'object') {
for (j = 0, k = subscriber[x].length; j < k; j++) {
subscriber[x][j](e);
}
}
}
};
return f;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment