Skip to content

Instantly share code, notes, and snippets.

@sebmck
Created April 25, 2013 11:48
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 sebmck/5459167 to your computer and use it in GitHub Desktop.
Save sebmck/5459167 to your computer and use it in GitHub Desktop.
/**
* @file Description
*/
/**
* Description
*
* @constructor
*/
function EventEmitter(){
}
/**
* Description
*/
EventEmitter.prototype.initEvents = function(){
if (this._events) return;
this._events = {};
this._all = [];
};
/**
* Description
*
* @param {String} type
*/
EventEmitter.prototype.listeners = function(type){
this.initEvents();
var events = this._events[type];
return events ? events.clone : [];
};
/**
* Description
*
* @param {String} type
* @param {...} args
*/
EventEmitter.prototype.emit = function(type){
this.initEvents();
var listeners = this.listeners(type);
var self = this;
var args = arguments.toArray.slice(1);
listeners.each(function(fn){
fn.apply(self, args);
});
this._all.each(function(fn){
fn.call(self, type, args);
});
return this;
};
/**
* Description
*
* @param {String} type
* @param {Function} fn
*/
EventEmitter.prototype.on = function(type, fn){
this.initEvents();
var events = this._events[type] = this._events[type] || [];
events.push(fn);
return this;
};
/**
* Description
*
* @param {String} type
* @param {Function} fn
*/
EventEmitter.prototype.once = function(type, fn){
var self = this;
return this.on(type, function(){
fn.apply(this, arguments);
self.off(type, fn);
});
};
/**
* Description
*
* @param {String} [type]
* @param {Function} fn
*/
EventEmitter.prototype.off = function(type, fn){
this.initEvents();
if (!fn) {
fn = type;
type = null;
}
function check(arr){
if (!arr) return;
arr.each(function(val, key){
if (val === fn) arr.remove(key);
});
}
if (type) {
check(this._events[type]);
} else {
this._events.each(check);
}
return this;
};
/**
* Description
*
* @param {Function} fn
*/
EventEmitter.prototype.onAny = function(fn){
this.initEvents();
this._all.push(fn);
return this;
};
/**
* Description
*
* @param {Function} fn
*/
EventEmitter.prototype.offAny = function(fn){
this.initEvents();
var all = this._all;
all.each(function(val, key){
if (fn === val) all.remove(key);
});
return this;
};
/**
* Description
*
* @param {EventEmitter} to
* @param {String} [namespace]
*/
EventEmitter.prototype.proxy = function(to, namespace){
this.initEvents();
var from = this;
namespace = namespace ? namespace + " " : "";
from.onAny(function(type, args){
var listeners = to.listeners(namespace + type);
listeners.each(function(fn){
fn.apply(from, args);
});
});
return from;
};
module.exports = EventEmitter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment