Skip to content

Instantly share code, notes, and snippets.

@davethegr8
Last active August 29, 2015 14:05
Show Gist options
  • Save davethegr8/64db95f6ebd6bedd0478 to your computer and use it in GitHub Desktop.
Save davethegr8/64db95f6ebd6bedd0478 to your computer and use it in GitHub Desktop.
event emitters from the CJS2014 talk
var ee = createEE()
ee.emit('foo', [1, 2, 3])
ee.on('bar', function (a, b, c) {
console.log('bar: ' + a);
return b;
});
console.log('emit returned: ' + ee.emit('bar', [1, 2, 3]));
function createEE() {
var events = {};
function on (type, handler) {
events[type] = listeners(type).concat(handler);
}
function off (type, handler) {
var fns = listeners(type);
events[type] = fns.splice(fns.indexOf(handlers), 1)
}
function listeners (type) {
return events[type] || []
}
function emit (type, args) {
var self = this,
fns = listeners(type);
return fns.map(function (fn) {
return fn.apply(self, args)
});
}
return {
"on": on,
"off": off,
"emit": emit,
"listeners": listeners,
"events": events
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment