Created
February 24, 2014 09:58
-
-
Save f5io/9184869 to your computer and use it in GitHub Desktop.
Publish/Subscribe implementation
This file contains 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
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