Created
March 5, 2014 23:39
-
-
Save WebReflection/9379077 to your computer and use it in GitHub Desktop.
Simplified EventEmitter like objects
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
function createEmitter() { | |
// not ideal when many simple emitters are needed | |
// returns object similar to node.js EventEmitter API | |
// not compatible with DOM nodes, only JS controllers | |
var | |
// on, off, emit as immutable and non enumerable | |
// all methods returns the implicitly bound emitter | |
emitter = Object.create(null, { | |
on: {value: function (type, handler) { | |
var tmp = get(type); | |
if (tmp.indexOf(handler) < 0) { | |
tmp.push(handler); | |
} | |
return emitter; | |
}}, | |
off: {value: function (type, handler) { | |
var tmp = get(type), i = tmp.indexOf(handler); | |
if (-1 < i) { | |
tmp.splice(i, 1); | |
} | |
return emitter; | |
}}, | |
emit: {value: function (type, handler) { | |
var tmp = get(type); | |
tmp.forEach( | |
emit, | |
tmp.slice.call(arguments, 1) | |
); | |
return emitter; | |
}} | |
}), | |
// private Dictionary for listeners | |
listeners = Object.create(null) | |
; | |
// private methods | |
function emit(handler) { | |
handler.apply(emitter, this); | |
} | |
function get(type) { | |
return listeners[type] || (listeners[type] = []); | |
} | |
return emitter; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment