3 * Copyright(c) 2006-2009 Ext JS, LLC
5 * http://www.extjs.com/license
8 * @class Ext.EventManager
\r
9 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
\r
10 * several useful events directly.
\r
11 * See {@link Ext.EventObject} for more details on normalized event objects.
\r
14 Ext.EventManager = function(){
\r
17 docReadyState = false,
\r
22 IEDEFERED = "ie-deferred-loader",
\r
23 DOMCONTENTLOADED = "DOMContentLoaded",
\r
24 propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,
\r
26 * This cache is used to hold special js objects, the document and window, that don't have an id. We need to keep
\r
27 * a reference to them so we can look them up at a later point.
\r
29 specialElCache = [];
\r
34 len = specialElCache.length,
\r
39 if(el.getElementById || el.navigator){
\r
41 for(; i < len; ++i){
\r
42 o = specialElCache[i];
\r
49 // for browsers that support it, ensure that give the el the same id
\r
51 specialElCache.push({
\r
60 if(!Ext.elCache[id]){
\r
61 Ext.Element.addToCache(new Ext.Element(el), id);
\r
63 Ext.elCache[id].skipGC = true;
\r
70 /// There is some jquery work around stuff here that isn't needed in Ext Core.
\r
71 function addListener(el, ename, fn, wrap, scope){
\r
72 el = Ext.getDom(el);
\r
74 es = Ext.elCache[id].events,
\r
77 wfn = E.on(el, ename, wrap);
\r
78 es[ename] = es[ename] || [];
\r
79 es[ename].push([fn, wrap, scope, wfn]);
\r
81 // this is a workaround for jQuery and should somehow be removed from Ext Core in the future
\r
82 // without breaking ExtJS.
\r
83 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
\r
84 var args = ["DOMMouseScroll", wrap, false];
\r
85 el.addEventListener.apply(el, args);
\r
86 Ext.EventManager.addListener(WINDOW, 'unload', function(){
\r
87 el.removeEventListener.apply(el, args);
\r
90 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
\r
91 Ext.EventManager.stoppedMouseDownEvent.addListener(wrap);
\r
95 function fireDocReady(){
\r
97 Ext.isReady = docReadyState = true;
\r
99 clearInterval(docReadyProcId);
\r
101 if(Ext.isGecko || Ext.isOpera) {
\r
102 DOC.removeEventListener(DOMCONTENTLOADED, fireDocReady, false);
\r
105 var defer = DOC.getElementById(IEDEFERED);
\r
107 defer.onreadystatechange = null;
\r
108 defer.parentNode.removeChild(defer);
\r
112 docReadyEvent.fire();
\r
113 docReadyEvent.listeners = []; // clearListeners no longer compatible. Force single: true?
\r
118 function initDocReady(){
\r
119 var COMPLETE = "complete";
\r
121 docReadyEvent = new Ext.util.Event();
\r
122 if (Ext.isGecko || Ext.isOpera) {
\r
123 DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false);
\r
124 } else if (Ext.isIE){
\r
125 DOC.write("<s"+'cript id=' + IEDEFERED + ' defer="defer" src="/'+'/:"></s'+"cript>");
\r
126 DOC.getElementById(IEDEFERED).onreadystatechange = function(){
\r
127 if(this.readyState == COMPLETE){
\r
131 } else if (Ext.isWebKit){
\r
132 docReadyProcId = setInterval(function(){
\r
133 if(DOC.readyState == COMPLETE) {
\r
138 // no matter what, make sure it fires on load
\r
139 E.on(WINDOW, "load", fireDocReady);
\r
142 function createTargeted(h, o){
\r
144 var args = Ext.toArray(arguments);
\r
145 if(o.target == Ext.EventObject.setEvent(args[0]).target){
\r
146 h.apply(this, args);
\r
151 function createBuffered(h, o, fn){
\r
152 fn.task = new Ext.util.DelayedTask(h);
\r
153 var w = function(e){
\r
154 // create new event object impl so new events don't wipe out properties
\r
155 fn.task.delay(o.buffer, h, null, [new Ext.EventObjectImpl(e)]);
\r
160 function createSingle(h, el, ename, fn, scope){
\r
161 return function(e){
\r
162 Ext.EventManager.removeListener(el, ename, fn, scope);
\r
167 function createDelayed(h, o, fn){
\r
168 return function(e){
\r
169 var task = new Ext.util.DelayedTask(h);
\r
173 fn.tasks.push(task);
\r
174 task.delay(o.delay || 10, h, null, [new Ext.EventObjectImpl(e)]);
\r
178 function listen(element, ename, opt, fn, scope){
\r
179 var o = !Ext.isObject(opt) ? {} : opt,
\r
180 el = Ext.getDom(element);
\r
183 scope = scope || o.scope;
\r
186 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
\r
189 // prevent errors while unload occurring
\r
190 if(!Ext){// !window[xname]){ ==> can't we do this?
\r
193 e = Ext.EventObject.setEvent(e);
\r
196 if(!(t = e.getTarget(o.delegate, el))){
\r
205 if (o.preventDefault) {
\r
206 e.preventDefault();
\r
208 if (o.stopPropagation) {
\r
209 e.stopPropagation();
\r
211 if (o.normalized) {
\r
212 e = e.browserEvent;
\r
215 fn.call(scope || el, e, t, o);
\r
218 h = createTargeted(h, o);
\r
221 h = createDelayed(h, o, fn);
\r
224 h = createSingle(h, el, ename, fn, scope);
\r
227 h = createBuffered(h, o, fn);
\r
230 addListener(el, ename, fn, h, scope);
\r
236 * Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will
\r
237 * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
\r
238 * @param {String/HTMLElement} el The html element or id to assign the event handler to.
\r
239 * @param {String} eventName The name of the event to listen for.
\r
240 * @param {Function} handler The handler function the event invokes. This function is passed
\r
241 * the following parameters:<ul>
\r
242 * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
\r
243 * <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event.
\r
244 * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
\r
245 * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
\r
247 * @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>.
\r
248 * @param {Object} options (optional) An object containing handler configuration properties.
\r
249 * This may contain any of the following properties:<ul>
\r
250 * <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>
\r
251 * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
\r
252 * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
\r
253 * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
\r
254 * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
\r
255 * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
\r
256 * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
\r
257 * <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>
\r
258 * <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
\r
259 * by the specified number of milliseconds. If the event fires again within that time, the original
\r
260 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
\r
261 * <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>
\r
263 * <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p>
\r
265 addListener : function(element, eventName, fn, scope, options){
\r
266 if(Ext.isObject(eventName)){
\r
267 var o = eventName, e, val;
\r
270 if(!propRe.test(e)){
\r
271 if(Ext.isFunction(val)){
\r
273 listen(element, e, o, val, o.scope);
\r
275 // individual options
\r
276 listen(element, e, val);
\r
281 listen(element, eventName, options, fn, scope);
\r
286 * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically
\r
287 * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
\r
288 * @param {String/HTMLElement} el The id or html element from which to remove the listener.
\r
289 * @param {String} eventName The name of the event.
\r
290 * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
\r
291 * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
\r
292 * then this must refer to the same object.
\r
294 removeListener : function(el, eventName, fn, scope){
\r
295 el = Ext.getDom(el);
\r
296 var id = getId(el),
\r
297 f = el && (Ext.elCache[id].events)[eventName] || [],
\r
300 for (i = 0, len = f.length; i < len; i++) {
\r
301 if (Ext.isArray(f[i]) && f[i][0] == fn && (!scope || f[i][2] == scope)) {
\r
306 k = fn.tasks && fn.tasks.length;
\r
309 fn.tasks[k].cancel();
\r
313 wf = wrap = f[i][1];
\r
314 if (E.extAdapter) {
\r
317 E.un(el, eventName, wf);
\r
319 if (f.length === 0) {
\r
320 delete Ext.elCache[id].events[eventName];
\r
322 for (k in Ext.elCache[id].events) {
\r
325 Ext.elCache[id].events = {};
\r
330 // jQuery workaround that should be removed from Ext Core
\r
331 if(eventName == "mousewheel" && el.addEventListener && wrap){
\r
332 el.removeEventListener("DOMMouseScroll", wrap, false);
\r
335 if(eventName == "mousedown" && el == DOC && wrap){ // fix stopped mousedowns on the document
\r
336 Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
\r
341 * Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners}
\r
342 * directly on an Element in favor of calling this version.
\r
343 * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
\r
345 removeAll : function(el){
\r
346 el = Ext.getDom(el);
\r
347 var id = getId(el),
\r
348 ec = Ext.elCache[id] || {},
\r
349 es = ec.events || {},
\r
350 f, i, len, ename, fn, k;
\r
353 if(es.hasOwnProperty(ename)){
\r
355 for (i = 0, len = f.length; i < len; i++) {
\r
361 if(fn.tasks && (k = fn.tasks.length)) {
\r
363 fn.tasks[k].cancel();
\r
367 E.un(el, ename, E.extAdapter ? f[i][3] : f[i][1]);
\r
371 if (Ext.elCache[id]) {
\r
372 Ext.elCache[id].events = {};
\r
376 getListeners : function(el, eventName) {
\r
377 el = Ext.getDom(el);
\r
378 var id = getId(el),
\r
379 ec = Ext.elCache[id] || {},
\r
380 es = ec.events || {},
\r
382 if (es && es[eventName]) {
\r
383 return es[eventName];
\r
389 purgeElement : function(el, recurse, eventName) {
\r
390 el = Ext.getDom(el);
\r
391 var id = getId(el),
\r
392 ec = Ext.elCache[id] || {},
\r
393 es = ec.events || {},
\r
396 if (es && es.hasOwnProperty(eventName)) {
\r
398 for (i = 0, len = f.length; i < len; i++) {
\r
399 Ext.EventManager.removeListener(el, eventName, f[i][0]);
\r
403 Ext.EventManager.removeAll(el);
\r
405 if (recurse && el && el.childNodes) {
\r
406 for (i = 0, len = el.childNodes.length; i < len; i++) {
\r
407 Ext.EventManager.purgeElement(el.childNodes[i], recurse, eventName);
\r
412 _unload : function() {
\r
414 for (el in Ext.elCache) {
\r
415 Ext.EventManager.removeAll(el);
\r
419 * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
\r
420 * accessed shorthanded as Ext.onReady().
\r
421 * @param {Function} fn The method the event invokes.
\r
422 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
\r
423 * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
\r
424 * <code>{single: true}</code> be used so that the handler is removed on first invocation.
\r
426 onDocumentReady : function(fn, scope, options){
\r
427 if(docReadyState){ // if it already fired
\r
428 docReadyEvent.addListener(fn, scope, options);
\r
429 docReadyEvent.fire();
\r
430 docReadyEvent.listeners = []; // clearListeners no longer compatible. Force single: true?
\r
432 if(!docReadyEvent) initDocReady();
\r
433 options = options || {};
\r
434 options.delay = options.delay || 1;
\r
435 docReadyEvent.addListener(fn, scope, options);
\r
440 * Appends an event handler to an element. Shorthand for {@link #addListener}.
\r
441 * @param {String/HTMLElement} el The html element or id to assign the event handler to
\r
442 * @param {String} eventName The name of the event to listen for.
\r
443 * @param {Function} handler The handler function the event invokes.
\r
444 * @param {Object} scope (optional) (<code>this</code> reference) in which the handler function executes. <b>Defaults to the Element</b>.
\r
445 * @param {Object} options (optional) An object containing standard {@link #addListener} options
\r
446 * @member Ext.EventManager
\r
449 pub.on = pub.addListener;
\r
451 * Removes an event handler from an element. Shorthand for {@link #removeListener}.
\r
452 * @param {String/HTMLElement} el The id or html element from which to remove the listener.
\r
453 * @param {String} eventName The name of the event.
\r
454 * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #on} call.</b>
\r
455 * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
\r
456 * then this must refer to the same object.
\r
457 * @member Ext.EventManager
\r
460 pub.un = pub.removeListener;
\r
462 pub.stoppedMouseDownEvent = new Ext.util.Event();
\r
466 * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Shorthand of {@link Ext.EventManager#onDocumentReady}.
\r
467 * @param {Function} fn The method the event invokes.
\r
468 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
\r
469 * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
\r
470 * <code>{single: true}</code> be used so that the handler is removed on first invocation.
\r
474 Ext.onReady = Ext.EventManager.onDocumentReady;
\r
477 //Initialize doc classes
\r
480 var initExtCss = function(){
\r
481 // find the body element
\r
482 var bd = document.body || document.getElementsByTagName('body')[0];
\r
483 if(!bd){ return false; }
\r
485 Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : (Ext.isIE7 ? 'ext-ie7' : 'ext-ie8'))
\r
486 : Ext.isGecko ? "ext-gecko " + (Ext.isGecko2 ? 'ext-gecko2' : 'ext-gecko3')
\r
487 : Ext.isOpera ? "ext-opera"
\r
488 : Ext.isWebKit ? "ext-webkit" : ""];
\r
491 cls.push("ext-safari " + (Ext.isSafari2 ? 'ext-safari2' : (Ext.isSafari3 ? 'ext-safari3' : 'ext-safari4')));
\r
492 }else if(Ext.isChrome){
\r
493 cls.push("ext-chrome");
\r
497 cls.push("ext-mac");
\r
500 cls.push("ext-linux");
\r
503 if(Ext.isStrict || Ext.isBorderBox){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
\r
504 var p = bd.parentNode;
\r
506 p.className += Ext.isStrict ? ' ext-strict' : ' ext-border-box';
\r
509 bd.className += cls.join(' ');
\r
514 Ext.onReady(initExtCss);
\r
520 * @class Ext.EventObject
\r
521 * Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject
\r
522 * wraps the browser's native event-object normalizing cross-browser differences,
\r
523 * such as which mouse button is clicked, keys pressed, mechanisms to stop
\r
524 * event-propagation along with a method to prevent default actions from taking place.
\r
525 * <p>For example:</p>
\r
527 function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
\r
528 e.preventDefault();
\r
529 var target = e.getTarget(); // same as t (the target HTMLElement)
\r
532 var myDiv = {@link Ext#get Ext.get}("myDiv"); // get reference to an {@link Ext.Element}
\r
533 myDiv.on( // 'on' is shorthand for addListener
\r
534 "click", // perform an action on click of myDiv
\r
535 handleClick // reference to the action handler
\r
537 // other methods to do the same:
\r
538 Ext.EventManager.on("myDiv", 'click', handleClick);
\r
539 Ext.EventManager.addListener("myDiv", 'click', handleClick);
\r
543 Ext.EventObject = function(){
\r
544 var E = Ext.lib.Event,
\r
545 // safari keypress events for special keys return bad keycodes
\r
548 63234 : 37, // left
\r
549 63235 : 39, // right
\r
551 63233 : 40, // down
\r
552 63276 : 33, // page up
\r
553 63277 : 34, // page down
\r
554 63272 : 46, // delete
\r
555 63273 : 36, // home
\r
558 // normalize button clicks
\r
559 btnMap = Ext.isIE ? {1:0,4:1,2:2} :
\r
560 (Ext.isWebKit ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
\r
562 Ext.EventObjectImpl = function(e){
\r
564 this.setEvent(e.browserEvent || e);
\r
568 Ext.EventObjectImpl.prototype = {
\r
570 setEvent : function(e){
\r
572 if(e == me || (e && e.browserEvent)){ // already wrapped
\r
575 me.browserEvent = e;
\r
577 // normalize buttons
\r
578 me.button = e.button ? btnMap[e.button] : (e.which ? e.which - 1 : -1);
\r
579 if(e.type == 'click' && me.button == -1){
\r
583 me.shiftKey = e.shiftKey;
\r
584 // mac metaKey behaves like ctrlKey
\r
585 me.ctrlKey = e.ctrlKey || e.metaKey || false;
\r
586 me.altKey = e.altKey;
\r
587 // in getKey these will be normalized for the mac
\r
588 me.keyCode = e.keyCode;
\r
589 me.charCode = e.charCode;
\r
590 // cache the target for the delayed and or buffered events
\r
591 me.target = E.getTarget(e);
\r
593 me.xy = E.getXY(e);
\r
596 me.shiftKey = false;
\r
597 me.ctrlKey = false;
\r
608 * Stop the event (preventDefault and stopPropagation)
\r
610 stopEvent : function(){
\r
612 if(me.browserEvent){
\r
613 if(me.browserEvent.type == 'mousedown'){
\r
614 Ext.EventManager.stoppedMouseDownEvent.fire(me);
\r
616 E.stopEvent(me.browserEvent);
\r
621 * Prevents the browsers default handling of the event.
\r
623 preventDefault : function(){
\r
624 if(this.browserEvent){
\r
625 E.preventDefault(this.browserEvent);
\r
630 * Cancels bubbling of the event.
\r
632 stopPropagation : function(){
\r
634 if(me.browserEvent){
\r
635 if(me.browserEvent.type == 'mousedown'){
\r
636 Ext.EventManager.stoppedMouseDownEvent.fire(me);
\r
638 E.stopPropagation(me.browserEvent);
\r
643 * Gets the character code for the event.
\r
646 getCharCode : function(){
\r
647 return this.charCode || this.keyCode;
\r
651 * Returns a normalized keyCode for the event.
\r
652 * @return {Number} The key code
\r
654 getKey : function(){
\r
655 return this.normalizeKey(this.keyCode || this.charCode)
\r
659 normalizeKey: function(k){
\r
660 return Ext.isSafari ? (safariKeys[k] || k) : k;
\r
664 * Gets the x coordinate of the event.
\r
667 getPageX : function(){
\r
672 * Gets the y coordinate of the event.
\r
675 getPageY : function(){
\r
680 * Gets the page coordinates of the event.
\r
681 * @return {Array} The xy values like [x, y]
\r
683 getXY : function(){
\r
688 * Gets the target for the event.
\r
689 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
\r
690 * @param {Number/Mixed} maxDepth (optional) The max depth to
\r
691 search as a number or element (defaults to 10 || document.body)
\r
692 * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
\r
693 * @return {HTMLelement}
\r
695 getTarget : function(selector, maxDepth, returnEl){
\r
696 return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target);
\r
700 * Gets the related target.
\r
701 * @return {HTMLElement}
\r
703 getRelatedTarget : function(){
\r
704 return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null;
\r
708 * Normalizes mouse wheel delta across browsers
\r
709 * @return {Number} The delta
\r
711 getWheelDelta : function(){
\r
712 var e = this.browserEvent;
\r
714 if(e.wheelDelta){ /* IE/Opera. */
\r
715 delta = e.wheelDelta/120;
\r
716 }else if(e.detail){ /* Mozilla case. */
\r
717 delta = -e.detail/3;
\r
723 * 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.
\r
724 * Example usage:<pre><code>
\r
725 // Handle click on any child of an element
\r
726 Ext.getBody().on('click', function(e){
\r
727 if(e.within('some-el')){
\r
728 alert('Clicked on a child of some-el!');
\r
732 // Handle click directly on an element, ignoring clicks on child nodes
\r
733 Ext.getBody().on('click', function(e,t){
\r
734 if((t.id == 'some-el') && !e.within(t, true)){
\r
735 alert('Clicked directly on some-el!');
\r
739 * @param {Mixed} el The id, DOM element or Ext.Element to check
\r
740 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
\r
741 * @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target
\r
742 * @return {Boolean}
\r
744 within : function(el, related, allowEl){
\r
746 var t = this[related ? "getRelatedTarget" : "getTarget"]();
\r
747 return t && ((allowEl ? (t == Ext.getDom(el)) : false) || Ext.fly(el).contains(t));
\r
753 return new Ext.EventObjectImpl();
\r