3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
8 * @class Ext.EventManager
9 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
10 * several useful events directly.
11 * See {@link Ext.EventObject} for more details on normalized event objects.
14 Ext.EventManager = function(){
17 docReadyState = false,
18 DETECT_NATIVE = Ext.isGecko || Ext.isWebKit || Ext.isSafari,
23 DOMCONTENTLOADED = "DOMContentLoaded",
24 COMPLETE = 'complete',
25 propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,
27 * This cache is used to hold special js objects, the document and window, that don't have an id. We need to keep
28 * a reference to them so we can look them up at a later point.
35 len = specialElCache.length,
40 if (el.getElementById || el.navigator) {
43 o = specialElCache[i];
50 // for browsers that support it, ensure that give the el the same id
62 Ext.Element.addToCache(new Ext.Element(el), id);
64 Ext.elCache[id].skipGC = true;
71 /// There is some jquery work around stuff here that isn't needed in Ext Core.
72 function addListener(el, ename, fn, task, wrap, scope){
75 es = Ext.elCache[id].events,
78 wfn = E.on(el, ename, wrap);
79 es[ename] = es[ename] || [];
81 /* 0 = Original Function,
82 1 = Event Manager Wrapped Function,
84 3 = Adapter Wrapped Function,
87 es[ename].push([fn, wrap, scope, wfn, task]);
89 // this is a workaround for jQuery and should somehow be removed from Ext Core in the future
90 // without breaking ExtJS.
92 // workaround for jQuery
93 if(el.addEventListener && ename == "mousewheel"){
94 var args = ["DOMMouseScroll", wrap, false];
95 el.addEventListener.apply(el, args);
96 Ext.EventManager.addListener(WINDOW, 'unload', function(){
97 el.removeEventListener.apply(el, args);
101 // fix stopped mousedowns on the document
102 if(el == DOC && ename == "mousedown"){
103 Ext.EventManager.stoppedMouseDownEvent.addListener(wrap);
107 function doScrollChk(){
109 'doScroll' will NOT work in a IFRAME/FRAMESET.
110 The method succeeds but, a DOM query done immediately after -- FAILS.
117 DOC.documentElement.doScroll('left');
126 * @return {Boolean} True if the document is in a 'complete' state (or was determined to
127 * be true by other means). If false, the state is evaluated again until canceled.
129 function checkReadyState(e){
131 if(Ext.isIE && doScrollChk()){
134 if(DOC.readyState == COMPLETE){
138 docReadyState || (docReadyProcId = setTimeout(arguments.callee, 2));
143 function checkStyleSheets(e){
144 styles || (styles = Ext.query('style, link[rel=stylesheet]'));
145 if(styles.length == DOC.styleSheets.length){
149 docReadyState || (docReadyProcId = setTimeout(arguments.callee, 2));
153 function OperaDOMContentLoaded(e){
154 DOC.removeEventListener(DOMCONTENTLOADED, arguments.callee, false);
158 function fireDocReady(e){
160 docReadyState = true; //only attempt listener removal once
163 clearTimeout(docReadyProcId);
166 DOC.removeEventListener(DOMCONTENTLOADED, fireDocReady, false);
168 if(Ext.isIE && checkReadyState.bindIE){ //was this was actually set ??
169 DOC.detachEvent('onreadystatechange', checkReadyState);
171 E.un(WINDOW, "load", arguments.callee);
173 if(docReadyEvent && !Ext.isReady){
175 docReadyEvent.fire();
176 docReadyEvent.listeners = [];
181 function initDocReady(){
182 docReadyEvent || (docReadyEvent = new Ext.util.Event());
184 DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false);
187 * Handle additional (exceptional) detection strategies here
190 //Use readystatechange as a backup AND primary detection mechanism for a FRAME/IFRAME
191 //See if page is already loaded
192 if(!checkReadyState()){
193 checkReadyState.bindIE = true;
194 DOC.attachEvent('onreadystatechange', checkReadyState);
197 }else if(Ext.isOpera ){
199 Opera needs special treatment needed here because CSS rules are NOT QUITE
200 available after DOMContentLoaded is raised.
203 //See if page is already loaded and all styleSheets are in place
204 (DOC.readyState == COMPLETE && checkStyleSheets()) ||
205 DOC.addEventListener(DOMCONTENTLOADED, OperaDOMContentLoaded, false);
207 }else if (Ext.isWebKit){
208 //Fallback for older Webkits without DOMCONTENTLOADED support
211 // no matter what, make sure it fires on load
212 E.on(WINDOW, "load", fireDocReady);
215 function createTargeted(h, o){
217 var args = Ext.toArray(arguments);
218 if(o.target == Ext.EventObject.setEvent(args[0]).target){
224 function createBuffered(h, o, task){
226 // create new event object impl so new events don't wipe out properties
227 task.delay(o.buffer, h, null, [new Ext.EventObjectImpl(e)]);
231 function createSingle(h, el, ename, fn, scope){
233 Ext.EventManager.removeListener(el, ename, fn, scope);
238 function createDelayed(h, o, fn){
240 var task = new Ext.util.DelayedTask(h);
245 task.delay(o.delay || 10, h, null, [new Ext.EventObjectImpl(e)]);
249 function listen(element, ename, opt, fn, scope){
250 var o = (!opt || typeof opt == "boolean") ? {} : opt,
251 el = Ext.getDom(element), task;
254 scope = scope || o.scope;
257 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
260 // prevent errors while unload occurring
261 if(!Ext){// !window[xname]){ ==> can't we do this?
264 e = Ext.EventObject.setEvent(e);
267 if(!(t = e.getTarget(o.delegate, el))){
276 if (o.preventDefault) {
279 if (o.stopPropagation) {
282 if (o.normalized === false) {
286 fn.call(scope || el, e, t, o);
289 h = createTargeted(h, o);
292 h = createDelayed(h, o, fn);
295 h = createSingle(h, el, ename, fn, scope);
298 task = new Ext.util.DelayedTask(h);
299 h = createBuffered(h, o, task);
302 addListener(el, ename, fn, task, h, scope);
308 * Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will
309 * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
310 * @param {String/HTMLElement} el The html element or id to assign the event handler to.
311 * @param {String} eventName The name of the event to listen for.
312 * @param {Function} handler The handler function the event invokes. This function is passed
313 * the following parameters:<ul>
314 * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
315 * <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event.
316 * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
317 * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
319 * @param {Object} scope (optional) The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.
320 * @param {Object} options (optional) An object containing handler configuration properties.
321 * This may contain any of the following properties:<ul>
322 * <li>scope : Object<div class="sub-desc">The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.</div></li>
323 * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
324 * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
325 * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
326 * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
327 * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
328 * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
329 * <li>single : Boolean<div class="sub-desc">True to add a handler to handle just the next firing of the event, and then remove itself.</div></li>
330 * <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
331 * by the specified number of milliseconds. If the event fires again within that time, the original
332 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
333 * <li>target : Element<div class="sub-desc">Only call the handler if the event was fired on the target Element, <i>not</i> if the event was bubbled up from a child node.</div></li>
335 * <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p>
337 addListener : function(element, eventName, fn, scope, options){
338 if(typeof eventName == 'object'){
339 var o = eventName, e, val;
343 if(Ext.isFunction(val)){
345 listen(element, e, o, val, o.scope);
347 // individual options
348 listen(element, e, val);
353 listen(element, eventName, options, fn, scope);
358 * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically
359 * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
360 * @param {String/HTMLElement} el The id or html element from which to remove the listener.
361 * @param {String} eventName The name of the event.
362 * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
363 * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
364 * then this must refer to the same object.
366 removeListener : function(el, eventName, fn, scope){
369 f = el && (Ext.elCache[id].events)[eventName] || [],
370 wrap, i, l, k, len, fnc;
372 for (i = 0, len = f.length; i < len; i++) {
374 /* 0 = Original Function,
375 1 = Event Manager Wrapped Function,
377 3 = Adapter Wrapped Function,
380 if (Ext.isArray(fnc = f[i]) && fnc[0] == fn && (!scope || fnc[2] == scope)) {
384 k = fn.tasks && fn.tasks.length;
387 fn.tasks[k].cancel();
392 E.un(el, eventName, E.extAdapter ? fnc[3] : wrap);
394 // jQuery workaround that should be removed from Ext Core
395 if(wrap && el.addEventListener && eventName == "mousewheel"){
396 el.removeEventListener("DOMMouseScroll", wrap, false);
399 // fix stopped mousedowns on the document
400 if(wrap && el == DOC && eventName == "mousedown"){
401 Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
405 if (f.length === 0) {
406 delete Ext.elCache[id].events[eventName];
408 for (k in Ext.elCache[id].events) {
411 Ext.elCache[id].events = {};
418 * Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners}
419 * directly on an Element in favor of calling this version.
420 * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
422 removeAll : function(el){
425 ec = Ext.elCache[id] || {},
426 es = ec.events || {},
427 f, i, len, ename, fn, k, wrap;
430 if(es.hasOwnProperty(ename)){
432 /* 0 = Original Function,
433 1 = Event Manager Wrapped Function,
435 3 = Adapter Wrapped Function,
438 for (i = 0, len = f.length; i < len; i++) {
443 if(fn[0].tasks && (k = fn[0].tasks.length)) {
445 fn[0].tasks[k].cancel();
450 E.un(el, ename, E.extAdapter ? fn[3] : wrap);
452 // jQuery workaround that should be removed from Ext Core
453 if(el.addEventListener && wrap && ename == "mousewheel"){
454 el.removeEventListener("DOMMouseScroll", wrap, false);
457 // fix stopped mousedowns on the document
458 if(wrap && el == DOC && ename == "mousedown"){
459 Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
464 if (Ext.elCache[id]) {
465 Ext.elCache[id].events = {};
469 getListeners : function(el, eventName) {
472 ec = Ext.elCache[id] || {},
473 es = ec.events || {},
475 if (es && es[eventName]) {
476 return es[eventName];
482 purgeElement : function(el, recurse, eventName) {
485 ec = Ext.elCache[id] || {},
486 es = ec.events || {},
489 if (es && es.hasOwnProperty(eventName)) {
491 for (i = 0, len = f.length; i < len; i++) {
492 Ext.EventManager.removeListener(el, eventName, f[i][0]);
496 Ext.EventManager.removeAll(el);
498 if (recurse && el && el.childNodes) {
499 for (i = 0, len = el.childNodes.length; i < len; i++) {
500 Ext.EventManager.purgeElement(el.childNodes[i], recurse, eventName);
505 _unload : function() {
507 for (el in Ext.elCache) {
508 Ext.EventManager.removeAll(el);
511 delete Ext.Element._flyweights;
513 // Abort any outstanding Ajax requests
518 (typeof ajax.conn == 'object') ? conn = ajax.conn : conn = {};
522 ajax.abort({conn: c, tId: tid});
527 * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
528 * accessed shorthanded as Ext.onReady().
529 * @param {Function} fn The method the event invokes.
530 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
531 * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
532 * <code>{single: true}</code> be used so that the handler is removed on first invocation.
534 onDocumentReady : function(fn, scope, options){
535 if (Ext.isReady) { // if it already fired or document.body is present
536 docReadyEvent || (docReadyEvent = new Ext.util.Event());
537 docReadyEvent.addListener(fn, scope, options);
538 docReadyEvent.fire();
539 docReadyEvent.listeners = [];
541 if (!docReadyEvent) {
544 options = options || {};
545 options.delay = options.delay || 1;
546 docReadyEvent.addListener(fn, scope, options);
551 * Forces a document ready state transition for the framework. Used when Ext is loaded
552 * into a DOM structure AFTER initial page load (Google API or other dynamic load scenario.
553 * Any pending 'onDocumentReady' handlers will be fired (if not already handled).
555 fireDocReady : fireDocReady
558 * Appends an event handler to an element. Shorthand for {@link #addListener}.
559 * @param {String/HTMLElement} el The html element or id to assign the event handler to
560 * @param {String} eventName The name of the event to listen for.
561 * @param {Function} handler The handler function the event invokes.
562 * @param {Object} scope (optional) (<code>this</code> reference) in which the handler function executes. <b>Defaults to the Element</b>.
563 * @param {Object} options (optional) An object containing standard {@link #addListener} options
564 * @member Ext.EventManager
567 pub.on = pub.addListener;
569 * Removes an event handler from an element. Shorthand for {@link #removeListener}.
570 * @param {String/HTMLElement} el The id or html element from which to remove the listener.
571 * @param {String} eventName The name of the event.
572 * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #on} call.</b>
573 * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
574 * then this must refer to the same object.
575 * @member Ext.EventManager
578 pub.un = pub.removeListener;
580 pub.stoppedMouseDownEvent = new Ext.util.Event();
584 * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Shorthand of {@link Ext.EventManager#onDocumentReady}.
585 * @param {Function} fn The method the event invokes.
586 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
587 * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
588 * <code>{single: true}</code> be used so that the handler is removed on first invocation.
592 Ext.onReady = Ext.EventManager.onDocumentReady;
595 //Initialize doc classes
597 var initExtCss = function() {
598 // find the body element
599 var bd = document.body || document.getElementsByTagName('body')[0];
605 Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : (Ext.isIE7 ? 'ext-ie7' : 'ext-ie8'))
606 : Ext.isGecko ? "ext-gecko " + (Ext.isGecko2 ? 'ext-gecko2' : 'ext-gecko3')
607 : Ext.isOpera ? "ext-opera"
608 : Ext.isWebKit ? "ext-webkit" : ""];
611 cls.push("ext-safari " + (Ext.isSafari2 ? 'ext-safari2' : (Ext.isSafari3 ? 'ext-safari3' : 'ext-safari4')));
612 } else if(Ext.isChrome) {
613 cls.push("ext-chrome");
620 cls.push("ext-linux");
623 // add to the parent to allow for selectors like ".ext-strict .ext-ie"
624 if (Ext.isStrict || Ext.isBorderBox) {
625 var p = bd.parentNode;
627 Ext.fly(p, '_internal').addClass(((Ext.isStrict && Ext.isIE ) || (!Ext.enableForcedBoxModel && !Ext.isIE)) ? ' ext-strict' : ' ext-border-box');
630 // Forced border box model class applied to all elements. Bypassing javascript based box model adjustments
631 // in favor of css. This is for non-IE browsers.
632 if (Ext.enableForcedBoxModel && !Ext.isIE) {
633 Ext.isForcedBorderBox = true;
634 cls.push("ext-forced-border-box");
637 Ext.fly(bd, '_internal').addClass(cls);
642 * Assert Ext.isReady here. If Ext is loaded after the document is ready, none of the native
643 * DOM onReady events will fire, because they have already passed.
645 Ext.isReady = initExtCss();
648 Ext.onReady(initExtCss);
653 * Code used to detect certain browser feature/quirks/bugs at startup.
656 var supports = Ext.apply(Ext.supports, {
658 * In Webkit, there is an issue with getting the margin right property, see
659 * https://bugs.webkit.org/show_bug.cgi?id=13343
661 correctRightMargin: true,
664 * Webkit browsers return rgba(0, 0, 0) when a transparent color is used
666 correctTransparentColor: true,
669 * IE uses styleFloat, not cssFloat for the float property.
674 var supportTests = function(){
675 var div = document.createElement('div'),
680 div.innerHTML = '<div style="height:30px;width:50px;"><div style="height:20px;width:20px;"></div></div><div style="float:left;background-color:transparent;">';
681 doc.body.appendChild(div);
682 last = div.lastChild;
684 if((view = doc.defaultView)){
685 if(view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px'){
686 supports.correctRightMargin = false;
688 if(view.getComputedStyle(last, null).backgroundColor != 'transparent'){
689 supports.correctTransparentColor = false;
692 supports.cssFloat = !!last.style.cssFloat;
693 doc.body.removeChild(div);
699 Ext.onReady(supportTests);
705 * @class Ext.EventObject
706 * Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject
707 * wraps the browser's native event-object normalizing cross-browser differences,
708 * such as which mouse button is clicked, keys pressed, mechanisms to stop
709 * event-propagation along with a method to prevent default actions from taking place.
710 * <p>For example:</p>
712 function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
714 var target = e.getTarget(); // same as t (the target HTMLElement)
717 var myDiv = {@link Ext#get Ext.get}("myDiv"); // get reference to an {@link Ext.Element}
718 myDiv.on( // 'on' is shorthand for addListener
719 "click", // perform an action on click of myDiv
720 handleClick // reference to the action handler
722 // other methods to do the same:
723 Ext.EventManager.on("myDiv", 'click', handleClick);
724 Ext.EventManager.addListener("myDiv", 'click', handleClick);
728 Ext.EventObject = function(){
729 var E = Ext.lib.Event,
730 clickRe = /(dbl)?click/,
731 // safari keypress events for special keys return bad keycodes
738 63276 : 33, // page up
739 63277 : 34, // page down
740 63272 : 46, // delete
744 // normalize button clicks
745 btnMap = Ext.isIE ? {1:0,4:1,2:2} : {0:0,1:1,2:2};
747 Ext.EventObjectImpl = function(e){
749 this.setEvent(e.browserEvent || e);
753 Ext.EventObjectImpl.prototype = {
755 setEvent : function(e){
757 if(e == me || (e && e.browserEvent)){ // already wrapped
763 me.button = e.button ? btnMap[e.button] : (e.which ? e.which - 1 : -1);
764 if(clickRe.test(e.type) && me.button == -1){
768 me.shiftKey = e.shiftKey;
769 // mac metaKey behaves like ctrlKey
770 me.ctrlKey = e.ctrlKey || e.metaKey || false;
771 me.altKey = e.altKey;
772 // in getKey these will be normalized for the mac
773 me.keyCode = e.keyCode;
774 me.charCode = e.charCode;
775 // cache the target for the delayed and or buffered events
776 me.target = E.getTarget(e);
793 * Stop the event (preventDefault and stopPropagation)
795 stopEvent : function(){
798 if(me.browserEvent.type == 'mousedown'){
799 Ext.EventManager.stoppedMouseDownEvent.fire(me);
801 E.stopEvent(me.browserEvent);
806 * Prevents the browsers default handling of the event.
808 preventDefault : function(){
809 if(this.browserEvent){
810 E.preventDefault(this.browserEvent);
815 * Cancels bubbling of the event.
817 stopPropagation : function(){
820 if(me.browserEvent.type == 'mousedown'){
821 Ext.EventManager.stoppedMouseDownEvent.fire(me);
823 E.stopPropagation(me.browserEvent);
828 * Gets the character code for the event.
831 getCharCode : function(){
832 return this.charCode || this.keyCode;
836 * Returns a normalized keyCode for the event.
837 * @return {Number} The key code
840 return this.normalizeKey(this.keyCode || this.charCode);
844 normalizeKey: function(k){
845 return Ext.isSafari ? (safariKeys[k] || k) : k;
849 * Gets the x coordinate of the event.
852 getPageX : function(){
857 * Gets the y coordinate of the event.
860 getPageY : function(){
865 * Gets the page coordinates of the event.
866 * @return {Array} The xy values like [x, y]
873 * Gets the target for the event.
874 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
875 * @param {Number/Mixed} maxDepth (optional) The max depth to
876 search as a number or element (defaults to 10 || document.body)
877 * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
878 * @return {HTMLelement}
880 getTarget : function(selector, maxDepth, returnEl){
881 return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target);
885 * Gets the related target.
886 * @return {HTMLElement}
888 getRelatedTarget : function(){
889 return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null;
893 * Normalizes mouse wheel delta across browsers
894 * @return {Number} The delta
896 getWheelDelta : function(){
897 var e = this.browserEvent;
899 if(e.wheelDelta){ /* IE/Opera. */
900 delta = e.wheelDelta/120;
901 }else if(e.detail){ /* Mozilla case. */
908 * Returns true if the target of this event is a child of el. Unless the allowEl parameter is set, it will return false if if the target is el.
909 * Example usage:<pre><code>
910 // Handle click on any child of an element
911 Ext.getBody().on('click', function(e){
912 if(e.within('some-el')){
913 alert('Clicked on a child of some-el!');
917 // Handle click directly on an element, ignoring clicks on child nodes
918 Ext.getBody().on('click', function(e,t){
919 if((t.id == 'some-el') && !e.within(t, true)){
920 alert('Clicked directly on some-el!');
924 * @param {Mixed} el The id, DOM element or Ext.Element to check
925 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
926 * @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target
929 within : function(el, related, allowEl){
931 var t = this[related ? "getRelatedTarget" : "getTarget"]();
932 return t && ((allowEl ? (t == Ext.getDom(el)) : false) || Ext.fly(el).contains(t));
938 return new Ext.EventObjectImpl();