Created
July 7, 2015 21:40
-
-
Save A-gambit/80623890c8b5a828911b to your computer and use it in GitHub Desktop.
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
function emitter(obj){ | |
var store = {} | |
obj.on = function (e, cb) { | |
add(e, cb, true) | |
} | |
obj.one = function (e, cb) { | |
add(e, cb, false) | |
} | |
obj.off = function (e) { | |
delete store[e] | |
} | |
obj.emit = function (e) { | |
var events = store[e] || [] | |
var args = Array.prototype.slice.call(arguments, 1) | |
events.forEach(function(cb, i) { | |
cb(args, i) | |
}) | |
} | |
return obj | |
function add(e, cb, t) { | |
store[e] = store[e] || [] | |
store[e].push(function (args, i) { | |
cb.apply(obj, args) | |
if (!t) store[e].splice(i,1) | |
}) | |
} | |
} | |
var a = emitter({ | |
some: 123 | |
}) | |
a.on('roof-on-fire', function () { | |
console.log('put the fire', this.some) | |
}) | |
a.one('roof-on-fire', function (data) { | |
console.log('call the fireman', data) | |
}) | |
a.emit('roof-on-fire', { address: '560, Mission st.'}) | |
a.off('roof-on-fire') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment