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.
15 Ext.EventManager = function(){
18 docReadyState = false,
19 DETECT_NATIVE = Ext.isGecko || Ext.isWebKit || Ext.isSafari,
24 DOMCONTENTLOADED = "DOMContentLoaded",
25 COMPLETE = 'complete',
26 propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,
28 * This cache is used to hold special js objects, the document and window, that don't have an id. We need to keep
29 * a reference to them so we can look them up at a later point.
36 len = specialElCache.length,
41 if(el.getElementById || el.navigator){
44 o = specialElCache[i];
51 // for browsers that support it, ensure that give the el the same id
63 Ext.Element.addToCache(new Ext.Element(el), id);
65 Ext.elCache[id].skipGC = true;
72 /// There is some jquery work around stuff here that isn't needed in Ext Core.
73 function addListener(el, ename, fn, task, wrap, scope){
76 es = Ext.elCache[id].events,
79 wfn = E.on(el, ename, wrap);
80 es[ename] = es[ename] || [];
82 /* 0 = Original Function,
83 1 = Event Manager Wrapped Function,
85 3 = Adapter Wrapped Function,
88 es[ename].push([fn, wrap, scope, wfn, task]);
90 // this is a workaround for jQuery and should somehow be removed from Ext Core in the future
91 // without breaking ExtJS.
93 // workaround for jQuery
94 if(el.addEventListener && ename == "mousewheel"){
95 var args = ["DOMMouseScroll", wrap, false];
96 el.addEventListener.apply(el, args);
97 Ext.EventManager.addListener(WINDOW, 'unload', function(){
98 el.removeEventListener.apply(el, args);
102 // fix stopped mousedowns on the document
103 if(el == DOC && ename == "mousedown"){
104 Ext.EventManager.stoppedMouseDownEvent.addListener(wrap);
108 function doScrollChk(){
110 'doScroll' will NOT work in a IFRAME/FRAMESET.
111 The method succeeds but, a DOM query done immediately after -- FAILS.
118 DOC.documentElement.doScroll('left');
127 * @return {Boolean} True if the document is in a 'complete' state (or was determined to
128 * be true by other means). If false, the state is evaluated again until canceled.
130 function checkReadyState(e){
132 if(Ext.isIE && doScrollChk()){
135 if(DOC.readyState == COMPLETE){
139 docReadyState || (docReadyProcId = setTimeout(arguments.callee, 2));
144 function checkStyleSheets(e){
145 styles || (styles = Ext.query('style, link[rel=stylesheet]'));
146 if(styles.length == DOC.styleSheets.length){
150 docReadyState || (docReadyProcId = setTimeout(arguments.callee, 2));
154 function OperaDOMContentLoaded(e){
155 DOC.removeEventListener(DOMCONTENTLOADED, arguments.callee, false);
159 function fireDocReady(e){
161 docReadyState = true; //only attempt listener removal once
164 clearTimeout(docReadyProcId);
167 DOC.removeEventListener(DOMCONTENTLOADED, fireDocReady, false);
169 if(Ext.isIE && checkReadyState.bindIE){ //was this was actually set ??
170 DOC.detachEvent('onreadystatechange', checkReadyState);
172 E.un(WINDOW, "load", arguments.callee);
174 if(docReadyEvent && !Ext.isReady){
176 docReadyEvent.fire();
177 docReadyEvent.listeners = [];
182 function initDocReady(){
183 docReadyEvent || (docReadyEvent = new Ext.util.Event());
185 DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false);
188 * Handle additional (exceptional) detection strategies here
191 //Use readystatechange as a backup AND primary detection mechanism for a FRAME/IFRAME
192 //See if page is already loaded
193 if(!checkReadyState()){
194 checkReadyState.bindIE = true;
195 DOC.attachEvent('onreadystatechange', checkReadyState);
198 }else if(Ext.isOpera ){
200 Opera needs special treatment needed here because CSS rules are NOT QUITE
201 available after DOMContentLoaded is raised.
204 //See if page is already loaded and all styleSheets are in place
205 (DOC.readyState == COMPLETE && checkStyleSheets()) ||
206 DOC.addEventListener(DOMCONTENTLOADED, OperaDOMContentLoaded, false);
208 }else if (Ext.isWebKit){
209 //Fallback for older Webkits without DOMCONTENTLOADED support
212 // no matter what, make sure it fires on load
213 E.on(WINDOW, "load", fireDocReady);
216 function createTargeted(h, o){
218 var args = Ext.toArray(arguments);
219 if(o.target == Ext.EventObject.setEvent(args[0]).target){
225 function createBuffered(h, o, task){
227 // create new event object impl so new events don't wipe out properties
228 task.delay(o.buffer, h, null, [new Ext.EventObjectImpl(e)]);
232 function createSingle(h, el, ename, fn, scope){
234 Ext.EventManager.removeListener(el, ename, fn, scope);
239 function createDelayed(h, o, fn){
241 var task = new Ext.util.DelayedTask(h);
246 task.delay(o.delay || 10, h, null, [new Ext.EventObjectImpl(e)]);
250 function listen(element, ename, opt, fn, scope){
251 var o = (!opt || typeof opt == "boolean") ? {} : opt,
252 el = Ext.getDom(element), task;
255 scope = scope || o.scope;
258 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
261 // prevent errors while unload occurring
262 if(!Ext){// !window[xname]){ ==> can't we do this?
265 e = Ext.EventObject.setEvent(e);
268 if(!(t = e.getTarget(o.delegate, el))){
277 if (o.preventDefault) {
280 if (o.stopPropagation) {
287 fn.call(scope || el, e, t, o);
290 h = createTargeted(h, o);
293 h = createDelayed(h, o, fn);
296 h = createSingle(h, el, ename, fn, scope);
299 task = new Ext.util.DelayedTask(h);
300 h = createBuffered(h, o, task);
303 addListener(el, ename, fn, task, h, scope);
309 * Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will
310 * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
311 * @param {String/HTMLElement} el The html element or id to assign the event handler to.
312 * @param {String} eventName The name of the event to listen for.
313 * @param {Function} handler The handler function the event invokes. This function is passed
314 * the following parameters:<ul>
315 * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
316 * <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event.
317 * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
318 * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
320 * @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>.
321 * @param {Object} options (optional) An object containing handler configuration properties.
322 * This may contain any of the following properties:<ul>
323 * <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>
324 * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
325 * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
326 * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
327 * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
328 * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
329 * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
330 * <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>
331 * <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
332 * by the specified number of milliseconds. If the event fires again within that time, the original
333 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
334 * <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>
336 * <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p>
338 addListener : function(element, eventName, fn, scope, options){
339 if(typeof eventName == 'object'){
340 var o = eventName, e, val;
344 if(Ext.isFunction(val)){
346 listen(element, e, o, val, o.scope);
348 // individual options
349 listen(element, e, val);
354 listen(element, eventName, options, fn, scope);
359 * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically
360 * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
361 * @param {String/HTMLElement} el The id or html element from which to remove the listener.
362 * @param {String} eventName The name of the event.
363 * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
364 * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
365 * then this must refer to the same object.
367 removeListener : function(el, eventName, fn, scope){
370 f = el && (Ext.elCache[id].events)[eventName] || [],
371 wrap, i, l, k, len, fnc;
373 for (i = 0, len = f.length; i < len; i++) {
375 /* 0 = Original Function,
376 1 = Event Manager Wrapped Function,
378 3 = Adapter Wrapped Function,
381 if (Ext.isArray(fnc = f[i]) && fnc[0] == fn && (!scope || fnc[2] == scope)) {
385 k = fn.tasks && fn.tasks.length;
388 fn.tasks[k].cancel();
393 E.un(el, eventName, E.extAdapter ? fnc[3] : wrap);
395 // jQuery workaround that should be removed from Ext Core
396 if(wrap && el.addEventListener && eventName == "mousewheel"){
397 el.removeEventListener("DOMMouseScroll", wrap, false);
400 // fix stopped mousedowns on the document
401 if(wrap && el == DOC && eventName == "mousedown"){
402 Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
406 if (f.length === 0) {
407 delete Ext.elCache[id].events[eventName];
409 for (k in Ext.elCache[id].events) {
412 Ext.elCache[id].events = {};
419 * Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners}
420 * directly on an Element in favor of calling this version.
421 * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
423 removeAll : function(el){
426 ec = Ext.elCache[id] || {},
427 es = ec.events || {},
428 f, i, len, ename, fn, k, wrap;
431 if(es.hasOwnProperty(ename)){
433 /* 0 = Original Function,
434 1 = Event Manager Wrapped Function,
436 3 = Adapter Wrapped Function,
439 for (i = 0, len = f.length; i < len; i++) {
444 if(fn[0].tasks && (k = fn[0].tasks.length)) {
446 fn[0].tasks[k].cancel();
451 E.un(el, ename, E.extAdapter ? fn[3] : wrap);
453 // jQuery workaround that should be removed from Ext Core
454 if(el.addEventListener && wrap && ename == "mousewheel"){
455 el.removeEventListener("DOMMouseScroll", wrap, false);
458 // fix stopped mousedowns on the document
459 if(wrap && el == DOC && ename == "mousedown"){
460 Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
465 if (Ext.elCache[id]) {
466 Ext.elCache[id].events = {};
470 getListeners : function(el, eventName) {
473 ec = Ext.elCache[id] || {},
474 es = ec.events || {},
476 if (es && es[eventName]) {
477 return es[eventName];
483 purgeElement : function(el, recurse, eventName) {
486 ec = Ext.elCache[id] || {},
487 es = ec.events || {},
490 if (es && es.hasOwnProperty(eventName)) {
492 for (i = 0, len = f.length; i < len; i++) {
493 Ext.EventManager.removeListener(el, eventName, f[i][0]);
497 Ext.EventManager.removeAll(el);
499 if (recurse && el && el.childNodes) {
500 for (i = 0, len = el.childNodes.length; i < len; i++) {
501 Ext.EventManager.purgeElement(el.childNodes[i], recurse, eventName);
506 _unload : function() {
508 for (el in Ext.elCache) {
509 Ext.EventManager.removeAll(el);
512 delete Ext.Element._flyweights;
514 // Abort any outstanding Ajax requests
519 (typeof ajax.conn == 'object') ? conn = ajax.conn : conn = {};
523 ajax.abort({conn: c, tId: tid});
528 * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
529 * accessed shorthanded as Ext.onReady().
530 * @param {Function} fn The method the event invokes.
531 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
532 * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
533 * <code>{single: true}</code> be used so that the handler is removed on first invocation.
535 onDocumentReady : function(fn, scope, options){
536 if(Ext.isReady){ // if it already fired or document.body is present
537 docReadyEvent || (docReadyEvent = new Ext.util.Event());
538 docReadyEvent.addListener(fn, scope, options);
539 docReadyEvent.fire();
540 docReadyEvent.listeners = [];
545 options = options || {};
546 options.delay = options.delay || 1;
547 docReadyEvent.addListener(fn, scope, options);
552 * Forces a document ready state transition for the framework. Used when Ext is loaded
553 * into a DOM structure AFTER initial page load (Google API or other dynamic load scenario.
554 * Any pending 'onDocumentReady' handlers will be fired (if not already handled).
556 fireDocReady : fireDocReady
559 * Appends an event handler to an element. Shorthand for {@link #addListener}.
560 * @param {String/HTMLElement} el The html element or id to assign the event handler to
561 * @param {String} eventName The name of the event to listen for.
562 * @param {Function} handler The handler function the event invokes.
563 * @param {Object} scope (optional) (<code>this</code> reference) in which the handler function executes. <b>Defaults to the Element</b>.
564 * @param {Object} options (optional) An object containing standard {@link #addListener} options
565 * @member Ext.EventManager
568 pub.on = pub.addListener;
570 * Removes an event handler from an element. Shorthand for {@link #removeListener}.
571 * @param {String/HTMLElement} el The id or html element from which to remove the listener.
572 * @param {String} eventName The name of the event.
573 * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #on} call.</b>
574 * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
575 * then this must refer to the same object.
576 * @member Ext.EventManager
579 pub.un = pub.removeListener;
581 pub.stoppedMouseDownEvent = new Ext.util.Event();
585 * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Shorthand of {@link Ext.EventManager#onDocumentReady}.
586 * @param {Function} fn The method the event invokes.
587 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
588 * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
589 * <code>{single: true}</code> be used so that the handler is removed on first invocation.
593 Ext.onReady = Ext.EventManager.onDocumentReady;
596 //Initialize doc classes
599 var initExtCss = function(){
600 // find the body element
601 var bd = document.body || document.getElementsByTagName('body')[0];
602 if(!bd){ return false; }
604 Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : (Ext.isIE7 ? 'ext-ie7' : 'ext-ie8'))
605 : Ext.isGecko ? "ext-gecko " + (Ext.isGecko2 ? 'ext-gecko2' : 'ext-gecko3')
606 : Ext.isOpera ? "ext-opera"
607 : Ext.isWebKit ? "ext-webkit" : ""];
610 cls.push("ext-safari " + (Ext.isSafari2 ? 'ext-safari2' : (Ext.isSafari3 ? 'ext-safari3' : 'ext-safari4')));
611 }else if(Ext.isChrome){
612 cls.push("ext-chrome");
619 cls.push("ext-linux");
622 if(Ext.isStrict || Ext.isBorderBox){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
623 var p = bd.parentNode;
625 p.className += Ext.isStrict ? ' ext-strict' : ' ext-border-box';
628 bd.className += cls.join(' ');
633 Ext.onReady(initExtCss);
639 * @class Ext.EventObject
640 * Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject
641 * wraps the browser's native event-object normalizing cross-browser differences,
642 * such as which mouse button is clicked, keys pressed, mechanisms to stop
643 * event-propagation along with a method to prevent default actions from taking place.
644 * <p>For example:</p>
646 function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
648 var target = e.getTarget(); // same as t (the target HTMLElement)
651 var myDiv = {@link Ext#get Ext.get}("myDiv"); // get reference to an {@link Ext.Element}
652 myDiv.on( // 'on' is shorthand for addListener
653 "click", // perform an action on click of myDiv
654 handleClick // reference to the action handler
656 // other methods to do the same:
657 Ext.EventManager.on("myDiv", 'click', handleClick);
658 Ext.EventManager.addListener("myDiv", 'click', handleClick);
662 Ext.EventObject = function(){
663 var E = Ext.lib.Event,
664 // safari keypress events for special keys return bad keycodes
671 63276 : 33, // page up
672 63277 : 34, // page down
673 63272 : 46, // delete
677 // normalize button clicks
678 btnMap = Ext.isIE ? {1:0,4:1,2:2} :
679 (Ext.isWebKit ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
681 Ext.EventObjectImpl = function(e){
683 this.setEvent(e.browserEvent || e);
687 Ext.EventObjectImpl.prototype = {
689 setEvent : function(e){
691 if(e == me || (e && e.browserEvent)){ // already wrapped
697 me.button = e.button ? btnMap[e.button] : (e.which ? e.which - 1 : -1);
698 if(e.type == 'click' && me.button == -1){
702 me.shiftKey = e.shiftKey;
703 // mac metaKey behaves like ctrlKey
704 me.ctrlKey = e.ctrlKey || e.metaKey || false;
705 me.altKey = e.altKey;
706 // in getKey these will be normalized for the mac
707 me.keyCode = e.keyCode;
708 me.charCode = e.charCode;
709 // cache the target for the delayed and or buffered events
710 me.target = E.getTarget(e);
727 * Stop the event (preventDefault and stopPropagation)
729 stopEvent : function(){
732 if(me.browserEvent.type == 'mousedown'){
733 Ext.EventManager.stoppedMouseDownEvent.fire(me);
735 E.stopEvent(me.browserEvent);
740 * Prevents the browsers default handling of the event.
742 preventDefault : function(){
743 if(this.browserEvent){
744 E.preventDefault(this.browserEvent);
749 * Cancels bubbling of the event.
751 stopPropagation : function(){
754 if(me.browserEvent.type == 'mousedown'){
755 Ext.EventManager.stoppedMouseDownEvent.fire(me);
757 E.stopPropagation(me.browserEvent);
762 * Gets the character code for the event.
765 getCharCode : function(){
766 return this.charCode || this.keyCode;
770 * Returns a normalized keyCode for the event.
771 * @return {Number} The key code
774 return this.normalizeKey(this.keyCode || this.charCode)
778 normalizeKey: function(k){
779 return Ext.isSafari ? (safariKeys[k] || k) : k;
783 * Gets the x coordinate of the event.
786 getPageX : function(){
791 * Gets the y coordinate of the event.
794 getPageY : function(){
799 * Gets the page coordinates of the event.
800 * @return {Array} The xy values like [x, y]
807 * Gets the target for the event.
808 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
809 * @param {Number/Mixed} maxDepth (optional) The max depth to
810 search as a number or element (defaults to 10 || document.body)
811 * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
812 * @return {HTMLelement}
814 getTarget : function(selector, maxDepth, returnEl){
815 return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target);
819 * Gets the related target.
820 * @return {HTMLElement}
822 getRelatedTarget : function(){
823 return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null;
827 * Normalizes mouse wheel delta across browsers
828 * @return {Number} The delta
830 getWheelDelta : function(){
831 var e = this.browserEvent;
833 if(e.wheelDelta){ /* IE/Opera. */
834 delta = e.wheelDelta/120;
835 }else if(e.detail){ /* Mozilla case. */
842 * 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.
843 * Example usage:<pre><code>
844 // Handle click on any child of an element
845 Ext.getBody().on('click', function(e){
846 if(e.within('some-el')){
847 alert('Clicked on a child of some-el!');
851 // Handle click directly on an element, ignoring clicks on child nodes
852 Ext.getBody().on('click', function(e,t){
853 if((t.id == 'some-el') && !e.within(t, true)){
854 alert('Clicked directly on some-el!');
858 * @param {Mixed} el The id, DOM element or Ext.Element to check
859 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
860 * @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target
863 within : function(el, related, allowEl){
865 var t = this[related ? "getRelatedTarget" : "getTarget"]();
866 return t && ((allowEl ? (t == Ext.getDom(el)) : false) || Ext.fly(el).contains(t));
872 return new Ext.EventObjectImpl();