Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created March 5, 2014 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/9379077 to your computer and use it in GitHub Desktop.
Save WebReflection/9379077 to your computer and use it in GitHub Desktop.
Simplified EventEmitter like objects
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