EventManager.js

/**
 * @class Ext.EventManager
 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides 
 * several useful events directly.
 * See {@link Ext.EventObject} for more details on normalized event objects.
 * @singleton
 */
Ext.EventManager = function(){
    var docReadyEvent;
    var docReadyProcId;
    var docReadyState = false;
    
    var resizeEvent;
    var resizeTask;
    var E = YAHOO.util.Event;
    var D = YAHOO.util.Dom;

    var fireDocReady = function(){
        if(!docReadyState){
            docReadyState = true;
            if(docReadyProcId){
                clearInterval(docReadyProcId);
            }
            if(docReadyEvent){
                docReadyEvent.fire();
                docReadyEvent.clearListeners();
            }
        }
    };
    
    var initDocReady = function(){
        docReadyEvent = new Ext.util.Event();
        if(document.addEventListener) {
            E.on(document, "DOMContentLoaded", fireDocReady);
        }else if(Ext.isIE){
            // inspired by  http://www.thefutureoftheweb.com/blog/2006/6/adddomloadevent
            document.write('<s'+'cript id="ie-deferred-loader" defer="defer" src="' +
                        (Ext.EventManager.ieDeferSrc || Ext.SSL_SECURE_URL) + '"></s'+'cript>');
            E.on('ie-deferred-loader', 'readystatechange', function(){
                if(this.readyState == 'complete'){
                    fireDocReady();
                }
            });
        }else if(Ext.isSafari){ 
            docReadyProcId = setInterval(function(){
                var rs = document.readyState;
                if(rs == 'loaded' || rs == 'complete') {
                    fireDocReady();     
                 }
            }, 10);
        }
        // no matter what, make sure it fires on load
        E.on(window, 'load', fireDocReady);
    };

    var createBuffered = function(h, o){
        var task = new Ext.util.DelayedTask(h);
        return function(e){
            e = Ext.EventObject.setEvent(e);
            task.delay(o.buffer, h, null, [e]);
        };
    };

    var createSingle = function(h, el, ename, fn){
        return function(e){
            Ext.EventManager.removeListener(el, ename, fn);
            h(e);
        };
    };

    var createDelayed = function(h, o){
        return function(e){
            e = Ext.EventObject.setEvent(e);
            setTimeout(function(){
                h(e);
            }, o.delay || 10);
        };
    };

    var listen = function(element, ename, opt, fn, scope){
        var o = (!opt || typeof opt == 'boolean') ? {} : opt;
        fn = fn || o.fn; scope = scope || o.scope;
        var el = typeof element == 'string' ?
                    document.getElementById(element) : element;
        if(!el){
            throw 'Error listening for ' + ename + '. Element ' + element + ' doesn\'t exist.';
        }
        var h = function(e){
            e = Ext.EventObject.setEvent(e);
            var t;
            if(o.delegate){
                t = e.getTarget(o.delegate, el);
                if(!t){
                    return;
                }
            }else{
                t = e.target;
            }
            if(o.stopEvent){
                e.stopEvent();
            }
            if(o.preventDefault){
               e.preventDefault();
            }
            if(o.stopPropagation){
                e.stopPropagation();
            }

            if(o.normalized === false){
                e = e.browserEvent;
            }

            fn.call(scope || el, e, t, o);
        };
        if(o.delay){
            h = createDelayed(h, o);
        }
        if(o.single){
            h = createSingle(h, el, ename, fn);
        }
        if(o.buffer){
            h = createBuffered(h, o);
        }

        fn._handlers = fn._handlers || [];
        fn._handlers.push([Ext.id(el), ename, h]);

        E.addListener(el, ename, h);
        if(ename == 'mousewheel'){
            E.addListener(el, 'DOMMouseScroll', h);
        }
        return h;
    };

    var stopListening = function(el, ename, fn){
        var id = Ext.id(el), hds = fn._handlers;
        if(hds){
            for(var i = 0, len = hds.length; i < len; i++){
                var h = hds[i];
                if(h[0] == id && h[1] == ename){
                    var hd = h[2];
                    hds.splice(i, 1);
                    return E.removeListener(el, ename, hd);
                }
            }
        }
        E.removeListener(el, ename, fn);
        if(ename == 'mousewheel'){
            E.removeListener(el, 'DOMMouseScroll', fn);
        }
    };

    var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized)$/;
    var pub = {
        
        /** 
         * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
         * object with a Ext.EventObject
         * @param {Function} fn        The method the event invokes
         * @param {Object}   scope    An object that becomes the scope of the handler
         * @param {boolean}  override If true, the obj passed in becomes
         *                             the execution scope of the listener
         * @return {Function} The wrapped function
         * @deprecated
         */
        wrap : function(fn, scope, override){
            return function(e){
                Ext.EventObject.setEvent(e);
                fn.call(override ? scope || window : window, Ext.EventObject, scope);
            };
        },
        
        /**
         * Appends an event handler
         *
         * @param {String/HTMLElement}   element        The html element or id to assign the 
         *                             event to
         * @param {String}   eventName     The type of event to append
         * @param {Function} fn        The method the event invokes
         * @param {Object}   options   An object with standard EventManager options
         */
        addListener : function(element, eventName, fn, scope, options){
            if(typeof eventName == 'object'){
                var o = eventName;
                for(var e in o){
                    if(propRe.test(e)){
                        continue;
                    }
                    if(typeof o[e] == 'function'){
                        // shared options
                        listen(element, e, o, o[e], o.scope);
                    }else{
                        // individual options
                        listen(element, e, o[e]);
                    }
                }
                return;
            }
            return listen(element, eventName, options, fn, scope);
        },
        
        /**
         * Removes an event handler
         *
         * @param {String/HTMLElement}   element        The id or html element to remove the 
         *                             event from
         * @param {String}   eventName     The type of event
         * @param {Function} fn
         * @return {Boolean} True if a listener was actually removed
         */
        removeListener : function(element, eventName, fn){
            return stopListening(element, eventName, fn);
        },
        
        /**
         * Fires when the document is ready (before onload and before images are loaded). Can be 
         * accessed shorthanded Ext.onReady().
         * @param {Function} fn        The method the event invokes
         * @param {Object}   scope    An  object that becomes the scope of the handler
         * @param {boolean}  options
         */
        onDocumentReady : function(fn, scope, options){
            if(docReadyState){ // if it already fired
                fn.call(override? scope || window : window, scope);
                return;
            }
            if(!docReadyEvent){
                initDocReady();
            }
            docReadyEvent.addListener(fn, scope, options);
        },
        
        /**
         * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
         * @param {Function} fn        The method the event invokes
         * @param {Object}   scope    An object that becomes the scope of the handler
         * @param {boolean}  override If true, the obj passed in becomes
         *                             the execution scope of the listener
         */
        onWindowResize : function(fn, scope, options){
            if(!resizeEvent){
                resizeEvent = new Ext.util.Event();
                resizeTask = new Ext.util.DelayedTask(function(){
                    resizeEvent.fire(D.getViewportWidth(), D.getViewportHeight());
                });
                E.on(window, 'resize', function(){
                    if(Ext.isIE){
                        resizeTask.delay(50);
                    }else{
                        resizeEvent.fire(D.getViewportWidth(), D.getViewportHeight());
                    }
                });
            }
            resizeEvent.addListener(fn, scope, options);
        },
        
        /**
         * Removes the passed window resize listener.
         * @param {Function} fn        The method the event invokes
         * @param {Object}   scope    The scope of handler
         */
        removeResizeListener : function(fn, scope){
            if(resizeEvent){
                resizeEvent.removeListener(fn, scope);
            }
        },
        
        fireResize : function(){
            if(resizeEvent){
                resizeEvent.fire(D.getViewportWidth(), D.getViewportHeight());
            }   
        },
        /**
         * Url used for onDocumentReady with using SSL (defaults to Ext.SSL_SECURE_URL)
         */
        ieDeferSrc : false
    };
    /**
     * Appends an event handler (shorthand for addListener)
     *
     * @param {String/HTMLElement}   element        The html element or id to assign the 
     *                             event to
     * @param {String}   eventName     The type of event to append
     * @param {Function} fn        The method the event invokes
     * @param {Object}   scope    An arbitrary object that will be 
     *                             passed as a parameter to the handler
     * @param {boolean}  override If true, the obj passed in becomes
     *                             the execution scope of the listener
     * @return {Function} The wrapper function created (to be used to remove the listener if necessary)
     * @method
     */
    pub.on = pub.addListener;

    return pub;
}();
/**
  * Fires when the document is ready (before onload and before images are loaded).  Shorthand of {@link Ext.EventManager#onDocumentReady}.
  * @param {Function} fn        The method the event invokes
  * @param {Object}   scope    An  object that becomes the scope of the handler
  * @param {boolean}  override If true, the obj passed in becomes
  *                             the execution scope of the listener
  * @member Ext
  * @method onReady
 */
Ext.onReady = Ext.EventManager.onDocumentReady;

Ext.onReady(function(){
        Ext.get(document.body).addClass(
                  Ext.isIE ? 'ext-ie'
                : Ext.isGecko ? 'ext-gecko'
                : Ext.isOpera ? 'ext-opera'
                : Ext.isSafari ? 'ext-safari' : '');
    });
/**
 * @class Ext.EventObject
 * EventObject exposes the Yahoo! UI Event functionality directly on the object
 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code 
 * (All the YAHOO.util.Event methods throw javascript errors if the passed event is null).
 * To get an EventObject instead of the standard browser event,
 * your must register your listener thru the {@link Ext.EventManager} or directly on an Element
 * with {@link Ext.Element#addManagedListener} or the shorthanded equivalent {@link Ext.Element#mon}.<br>
 * Example:
 * <pre><code>
 fu<>nction handleClick(e){ // e is not a standard event object, it is a Ext.EventObject
    e.preventDefault();
    var target = e.getTarget();
    ...
 }
 var myDiv = Ext.get('myDiv');
 myDiv.on('click', handleClick);
 //or
 Ext.EventManager.on('myDiv', 'click', handleClick);
 Ext.EventManager.addListener('myDiv', 'click', handleClick);
 </code></pre>
 * @singleton
 */
Ext.EventObject = function(){
    
    var E = YAHOO.util.Event;
    var D = YAHOO.util.Dom;

    // safari keypress events for special keys return bad keycodes
    var safariKeys = {
        63234 : 37, // left
        63235 : 39, // right
        63232 : 38, // up
        63233 : 40, // down
        63276 : 33, // page up
        63277 : 34, // page down
        63272 : 46, // delete
        63273 : 36, // home
        63275 : 35  // end
    };

    var btnMap = Ext.isIE ? {1:0,4:1,2:2} : {0:0,1:1,2:2};

    return {
    /** The normal browser event */ 
    browserEvent : null,
    /** The button pressed in a mouse event */ 
    button : -1,
    /** True if the shift key was down during the event */ 
    shiftKey : false,
    /** True if the control key was down during the event */ 
    ctrlKey : false,
    /** True if the alt key was down during the event */ 
    altKey : false,
    
    /** Key constant @type Number */
    BACKSPACE : 8,
    /** Key constant @type Number */
    TAB : 9,
    /** Key constant @type Number */
    RETURN : 13,
    /** Key constant @type Number */
    ENTER : 13,
    /** Key constant @type Number */
    ESC : 27,
    /** Key constant @type Number */
    SPACE : 32,
    /** Key constant @type Number */
    PAGEUP : 33,
    /** Key constant @type Number */
    PAGEDOWN : 34,
    /** Key constant @type Number */
    END : 35,
    /** Key constant @type Number */
    HOME : 36,
    /** Key constant @type Number */
    LEFT : 37,
    /** Key constant @type Number */
    UP : 38,
    /** Key constant @type Number */
    RIGHT : 39,
    /** Key constant @type Number */
    DOWN : 40,
    /** Key constant @type Number */
    DELETE : 46,
    /** Key constant @type Number */
    F5 : 116,

       /** @private */ 
    setEvent : function(e){
        if(e == this){ // already wrapped
            return this;
        }
        this.browserEvent = e;
        if(e){
            // normalize buttons
            this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
            this.shiftKey = e.shiftKey;
            // mac metaKey behaves like ctrlKey
            this.ctrlKey = e.ctrlKey || e.metaKey;
            this.altKey = e.altKey;
            // in getKey these will be normalized for the mac
            this.keyCode = e.keyCode;
            this.charCode = e.charCode;
            // cache the target for the delayed and or buffered events
            this.target = E.getTarget(e);
            // same for XY
            this.xy = E.getXY(e);
        }else{
            this.button = -1;
            this.shiftKey = false;
            this.ctrlKey = false;
            this.altKey = false;
            this.keyCode = 0;
            this.charCode =0;
            this.target = null;
            this.xy = [0, 0];
        }
        return this;
    },
    
    /**
     * Stop the event. Calls YAHOO.util.Event.stopEvent() if the event is not null.
     */ 
    stopEvent : function(){
        if(this.browserEvent){
            E.stopEvent(this.browserEvent);
        }
    },
    
    /**
     * Prevents the browsers default handling of the event. Calls YAHOO.util.Event.preventDefault() if the event is not null.
     */ 
    preventDefault : function(){
        if(this.browserEvent){
            E.preventDefault(this.browserEvent);
        }
    },
    
    /** @private */
    isNavKeyPress : function(){
        var k = this.getKey();
        return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
    },
    
    /**
     * Cancels bubbling of the event. Calls YAHOO.util.Event.stopPropagation() if the event is not null.
     */ 
    stopPropagation : function(){
        if(this.browserEvent){
            E.stopPropagation(this.browserEvent);
        }
    },
    
    /**
     * Gets the key code for the event. Returns value from YAHOO.util.Event.getCharCode() if the event is not null.
     * @return {Number}
     */ 
    getCharCode : function(){
        return this.charCode || this.keyCode;
    },
    
    /**
     * Returns a browsers key for a keydown event
     * @return {Number} The key code
     */
    getKey : function(){
        var k = this.keyCode || this.charCode;
        return Ext.isSafari ? (safariKeys[k] || k) : k;
    },
    
    /**
     * Gets the x coordinate of the event. Returns value from YAHOO.util.Event.getPageX() if the event is not null.
     * @return {Number}
     */ 
    getPageX : function(){
        return this.xy[0];
    },
    
    /**
     * Gets the y coordinate of the event. Returns value from YAHOO.util.Event.getPageY() if the event is not null.
     * @return {Number}
     */ 
    getPageY : function(){
        return this.xy[1];
    },
    
    /**
     * Gets the time of the event. Returns value from YAHOO.util.Event.getTime() if the event is not null.
     * @return {Number}
     */ 
    getTime : function(){
        if(this.browserEvent){
            return E.getTime(this.browserEvent);
        }
        return null;
    },
    
    /**
     * Gets the page coordinates of the event. Returns value from YAHOO.util.Event.getXY() if the event is not null.
     * @return {Array} The xy values like [x, y]
     */ 
    getXY : function(){
        return this.xy;
    },
    
    /**
     * Gets the target for the event.
     * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
     * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
            search as a number or element (defaults to 10 || document.body)
     * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
     * @return {HTMLelement}
     */ 
    getTarget : function(selector, maxDepth, returnEl){
        return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
    },
    /**
     * Gets the related target. Returns value from YAHOO.util.Event.getRelatedTarget() if the event is not null.
     * @return {HTMLElement}
     */ 
    getRelatedTarget : function(){
        if(this.browserEvent){
            return E.getRelatedTarget(this.browserEvent);
        }
        return null;
    },
    
    /**
     * Normalizes mouse wheel delta across browsers
     * @return {Number} The delta 
     */
    getWheelDelta : function(){
        var e = this.browserEvent;
        var delta = 0;
        if(e.wheelDelta){ /* IE/Opera. */
            delta = e.wheelDelta/120;
            /* In Opera 9, delta differs in sign as compared to IE. */
            if(window.opera) delta = -delta;
        }else if(e.detail){ /* Mozilla case. */
            delta = -e.detail/3;
        }
        return delta;
    },
    
    /**
     * Returns true if the control, shift or alt key was pressed during this event.
     * @return {Boolean}
     */ 
    hasModifier : function(){
        return ((this.ctrlKey || this.altKey) || this.shiftKey) ? true : false;
    },
    
    /**
     * Returns true if the target of this event equals el or is a child of el
     * @param {String/HTMLElement/Element} el
     * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
     * @return {Boolean}
     */
    within : function(el, related){
        var t = this[related ? 'getRelatedTarget' : 'getTarget']();
        return t && Ext.fly(el).contains(t);
    },
    
    getPoint : function(){
        return new YAHOO.util.Point(this.xy[0], this.xy[1]);
    }
    };
}();
            
    

yui-ext - Copyright © 2006 Jack Slocum. | Yahoo! UI - Copyright © 2006 Yahoo! Inc.
All rights reserved.