Last active
August 29, 2015 14:05
-
-
Save davethegr8/64db95f6ebd6bedd0478 to your computer and use it in GitHub Desktop.
event emitters from the CJS2014 talk
This file contains hidden or 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 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