Skip to content

Instantly share code, notes, and snippets.

@rendro
Last active December 18, 2015 01:48
Show Gist options
  • Save rendro/5706386 to your computer and use it in GitHub Desktop.
Save rendro/5706386 to your computer and use it in GitHub Desktop.
JavaScript Pub-Sub
var pubsub = (function () {
'use strict';
var observers = [];
return {
subscribe: function (events, listener) {
var event, i;
events = events.split(' ');
for (i in events) {
if (events.hasOwnProperty(i)) {
event = events[i];
(observers[event] || (observers[event] = [])).push(listener);
}
}
},
unsubscribe: function (event, listener) {
var value, key;
for (
value = observers[event] || [];
listener && (key = value.indexOf(listener)) > -1;
) {
value.splice(key, 1);
}
observers[event] = listener ? value : [];
},
publish: function (event) {
var args = Array.prototype.slice.call(arguments, 1);
for (
var value = observers[event], key = 0;
value && key < value.length;
) {
value[key++].apply(this, args);
}
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment