Skip to content

Instantly share code, notes, and snippets.

@A-gambit
Created July 7, 2015 21:40
Show Gist options
  • Save A-gambit/80623890c8b5a828911b to your computer and use it in GitHub Desktop.
Save A-gambit/80623890c8b5a828911b to your computer and use it in GitHub Desktop.
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