Rev. 2.73

/**
 * Extend API for the global event-oservers
 * 
 * @usage :
 *   this.load = Event.attach('load', function() {
 *     Archive = new Archive(true);
 *   });
 *   
 *   Event.destroy('load', this.load);
 */

var Events = Class.create({
  initialize: function() {
    this.observers = {
      // window events
      load:{}, unload:{}, scroll:{}, resize:{}, focus:{}, blur:{},
      // document event
      click:{}, dblclick:{}, 'dom:loaded':{}, 
      mouseup:{}, mousedown:{}, mousemove:{}, mouseover:{},
      keyup:{}, keydown:{}, keyPress:{}
    };

    // Align global event-oservers
    for (var evt in this.observers) {
      var obj = this.observers[evt];
    
      if (!obj) continue;
    
      // Get set functions
      var _callFunctions = (evt.match(/scroll|resize/)) ? function(bind, _obj) {
        if (Event.oserveTimeOut) {
          window.clearTimeout(Event.oserveTimeOut);
          delete Event.oserveTimeOut;
        }
        // Better performance for IE
        Event.oserveTimeOut = window.setTimeout(function() {
          for (var _func in _obj) _obj[_func](bind);
        }, 100);
      } : function(bind, _obj) {
        for (var _func in _obj) _obj[_func](bind);
      };
    
      // Observing Events;
      Event.observe((evt.match(/load|scroll|resize|focus|blur/))? window : document, evt, _callFunctions.bindAsEventListener(this, obj), false);
    }
    this.i = 0;

    Object.extend(Event, {
      attach: this.attach.bind(this),
      destroy: this.destroy.bind(this),
      callback: this.callback.bind(this)
    });
  },

  attach: function(action, func) {
    this.i++;
    if (this.observers[action] && typeof func == 'function') this.observers[action]['f' + this.i] = func;
    else return debug.error('Attach event error! wrong action name or missing function.');
    return 'f' + this.i;
  },

  destroy: function(action, execId) {
    if (typeof this.observers[action][execId] == 'function') delete this.observers[action][execId];
    else return Debug.error('Destroy event error! wrong action name or missing function id.');
  },

  callback: function(action, lookup) {
    var observers = this.observers[action];
    if (!lookup) for (var func in observers) observers[func]();
    return observers;
  }
});

new Events();

Comments

Got something to add? You can just leave a comment.

Your Reaction Time!

captcha

avatar