Skip to content

Instantly share code, notes, and snippets.

@f5io
Created February 24, 2014 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save f5io/9184869 to your computer and use it in GitHub Desktop.
Save f5io/9184869 to your computer and use it in GitHub Desktop.
Publish/Subscribe implementation
var _listeners = {};
function on() {
var args = [].slice.call(arguments);
var ev = args[0],
fn = args[1],
scope = args[2];
_listeners[ev] = _listeners[ev] || [];
_listeners[ev].push({ fn : fn, scope : scope });
}
function emit() {
var args = [].slice.call(arguments);
var ev = args[0],
props = args.slice(1);
if (!(ev in _listeners)) return;
for (var i in _listeners[ev]) {
var listener = _listeners[ev][i];
listener.fn.apply(listener.scope, props);
}
}
module.exports = {
on: on,
emit: emit
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment