Otaqui.com Blog

Javascript EventEmitter Mixin

/**
 * EventEmitter Mixin
 * 
 * Designed to be used in conjunction with a mixin "augment" function,
 * such as http://chamnapchhorn.blogspot.com/2009/05/javascript-mixins.html
 *
 * @usage augment(MyClass, EventEmitter);
 * my_inst = new MyClass();
 * my_inst.on('someEvent', function(e){ console.dir(e); });
 * my_inst.trigger('someEvent', {eventProp:'value'});
 */
var EventEmitter = function() {};
EventEmitter.prototype.on = function(name, callback, context) {
  if ( !context ) context = this;
  if ( !this._listeners ) this._listeners = {};
  if ( !this._listeners[name] ) this._listeners[name] = [];
  var f = function(e) { callback.apply(context, [e]); };
  this._listeners[name].push(f);
};
EventEmitter.prototype.trigger = function(name, event) {
  if ( !this._listeners ) this._listeners = {};
  if ( !this._listeners[name] ) return;
  var i = this._listeners[name].length;
  while ( i-- ) this._listeners[name][i](event);
};
EventEmitter.prototype.removeListener = function(name, callback) {
  if ( !this._listeners ) this._listeners = {};
  if ( !this._listeners[name] ) return;
  var i = this._listeners[name].length;
  while ( i-- ) {
    if ( this._listeners[name][i] === callback ) {
      this._listeners[name].splice(i, 1);
    }
  }
};