3 * Copyright(c) 2006-2009 Ext JS, LLC
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,
22 IEDEFERED = "ie-deferred-loader",
23 DOMCONTENTLOADED = "DOMContentLoaded",
25 propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
27 /// There is some jquery work around stuff here that isn't needed in Ext Core.
28 function addListener(el, ename, fn, wrap, scope){
30 es = elHash[id] = elHash[id] || {};
32 (es[ename] = es[ename] || []).push([fn, wrap, scope]);
33 E.on(el, ename, wrap);
35 // this is a workaround for jQuery and should somehow be removed from Ext Core in the future
36 // without breaking ExtJS.
37 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
38 var args = ["DOMMouseScroll", wrap, false];
39 el.addEventListener.apply(el, args);
40 E.on(window, 'unload', function(){
41 el.removeEventListener.apply(el, args);
44 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
45 Ext.EventManager.stoppedMouseDownEvent.addListener(wrap);
49 function fireDocReady(){
51 Ext.isReady = docReadyState = true;
53 clearInterval(docReadyProcId);
55 if(Ext.isGecko || Ext.isOpera) {
56 DOC.removeEventListener(DOMCONTENTLOADED, fireDocReady, false);
59 var defer = DOC.getElementById(IEDEFERED);
61 defer.onreadystatechange = null;
62 defer.parentNode.removeChild(defer);
67 docReadyEvent.clearListeners();
72 function initDocReady(){
73 var COMPLETE = "complete";
75 docReadyEvent = new Ext.util.Event();
76 if (Ext.isGecko || Ext.isOpera) {
77 DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false);
79 DOC.write("<s"+'cript id=' + IEDEFERED + ' defer="defer" src="/'+'/:"></s'+"cript>");
80 DOC.getElementById(IEDEFERED).onreadystatechange = function(){
81 if(this.readyState == COMPLETE){
85 } else if (Ext.isWebKit){
86 docReadyProcId = setInterval(function(){
87 if(DOC.readyState == COMPLETE) {
92 // no matter what, make sure it fires on load
93 E.on(WINDOW, "load", fireDocReady);
96 function createTargeted(h, o){
98 var args = Ext.toArray(arguments);
99 if(o.target == Ext.EventObject.setEvent(args[0]).target){
105 function createBuffered(h, o){
106 var task = new Ext.util.DelayedTask(h);
108 // create new event object impl so new events don't wipe out properties
109 task.delay(o.buffer, h, null, [new Ext.EventObjectImpl(e)]);
113 function createSingle(h, el, ename, fn, scope){
115 Ext.EventManager.removeListener(el, ename, fn, scope);
120 function createDelayed(h, o){
122 // create new event object impl so new events don't wipe out properties
123 e = new Ext.EventObjectImpl(e);
124 setTimeout(function(){
130 function listen(element, ename, opt, fn, scope){
131 var o = !Ext.isObject(opt) ? {} : opt,
132 el = Ext.getDom(element);
135 scope = scope || o.scope;
138 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
141 // prevent errors while unload occurring
142 if(!Ext){// !window[xname]){ ==> can't we do this?
145 e = Ext.EventObject.setEvent(e);
148 if(!(t = e.getTarget(o.delegate, el))){
157 if (o.preventDefault) {
160 if (o.stopPropagation) {
167 fn.call(scope || el, e, t, o);
170 h = createTargeted(h, o);
173 h = createDelayed(h, o);
176 h = createSingle(h, el, ename, fn, scope);
179 h = createBuffered(h, o);
182 addListener(el, ename, fn, h, scope);
188 * Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will
189 * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
190 * @param {String/HTMLElement} el The html element or id to assign the event handler to.
191 * @param {String} eventName The name of the event to listen for.
192 * @param {Function} handler The handler function the event invokes. This function is passed
193 * the following parameters:<ul>
194 * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
195 * <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event.
196 * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
197 * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
199 * @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>.
200 * @param {Object} options (optional) An object containing handler configuration properties.
201 * This may contain any of the following properties:<ul>
202 * <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>
203 * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
204 * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
205 * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
206 * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
207 * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
208 * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
209 * <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>
210 * <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
211 * by the specified number of milliseconds. If the event fires again within that time, the original
212 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
213 * <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>
215 * <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p>
217 addListener : function(element, eventName, fn, scope, options){
218 if(Ext.isObject(eventName)){
219 var o = eventName, e, val;
223 if(Ext.isFunction(val)){
225 listen(element, e, o, val, o.scope);
227 // individual options
228 listen(element, e, val);
233 listen(element, eventName, options, fn, scope);
238 * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically
239 * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
240 * @param {String/HTMLElement} el The id or html element from which to remove the listener.
241 * @param {String} eventName The name of the event.
242 * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
243 * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
244 * then this must refer to the same object.
246 removeListener : function(element, eventName, fn, scope){
247 var el = Ext.getDom(element),
251 Ext.each((elHash[id] || {})[eventName], function (v,i,a) {
252 if (Ext.isArray(v) && v[0] == fn && (!scope || v[2] == scope)) {
253 E.un(el, eventName, wrap = v[1]);
259 // jQuery workaround that should be removed from Ext Core
260 if(eventName == "mousewheel" && el.addEventListener && wrap){
261 el.removeEventListener("DOMMouseScroll", wrap, false);
264 if(eventName == "mousedown" && el == DOC && wrap){ // fix stopped mousedowns on the document
265 Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
270 * Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners}
271 * directly on an Element in favor of calling this version.
272 * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
274 removeAll : function(el){
275 var id = Ext.id(el = Ext.getDom(el)),
280 if(es.hasOwnProperty(ename)){
281 Ext.each(es[ename], function(v) {
282 E.un(el, ename, v.wrap);
290 * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
291 * accessed shorthanded as Ext.onReady().
292 * @param {Function} fn The method the event invokes.
293 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
294 * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
295 * <code>{single: true}</code> be used so that the handler is removed on first invocation.
297 onDocumentReady : function(fn, scope, options){
298 if(docReadyState){ // if it already fired
299 docReadyEvent.addListener(fn, scope, options);
300 docReadyEvent.fire();
301 docReadyEvent.clearListeners();
303 if(!docReadyEvent) initDocReady();
304 options = options || {};
305 options.delay = options.delay || 1;
306 docReadyEvent.addListener(fn, scope, options);
313 * Appends an event handler to an element. Shorthand for {@link #addListener}.
314 * @param {String/HTMLElement} el The html element or id to assign the event handler to
315 * @param {String} eventName The name of the event to listen for.
316 * @param {Function} handler The handler function the event invokes.
317 * @param {Object} scope (optional) (<code>this</code> reference) in which the handler function executes. <b>Defaults to the Element</b>.
318 * @param {Object} options (optional) An object containing standard {@link #addListener} options
319 * @member Ext.EventManager
322 pub.on = pub.addListener;
324 * Removes an event handler from an element. Shorthand for {@link #removeListener}.
325 * @param {String/HTMLElement} el The id or html element from which to remove the listener.
326 * @param {String} eventName The name of the event.
327 * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #on} call.</b>
328 * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
329 * then this must refer to the same object.
330 * @member Ext.EventManager
333 pub.un = pub.removeListener;
335 pub.stoppedMouseDownEvent = new Ext.util.Event();
339 * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Shorthand of {@link Ext.EventManager#onDocumentReady}.
340 * @param {Function} fn The method the event invokes.
341 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
342 * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
343 * <code>{single: true}</code> be used so that the handler is removed on first invocation.
347 Ext.onReady = Ext.EventManager.onDocumentReady;
350 //Initialize doc classes
353 var initExtCss = function(){
354 // find the body element
355 var bd = document.body || document.getElementsByTagName('body')[0];
356 if(!bd){ return false; }
358 Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : (Ext.isIE7 ? 'ext-ie7' : 'ext-ie8'))
359 : Ext.isGecko ? "ext-gecko " + (Ext.isGecko2 ? 'ext-gecko2' : 'ext-gecko3')
360 : Ext.isOpera ? "ext-opera"
361 : Ext.isWebKit ? "ext-webkit" : ""];
364 cls.push("ext-safari " + (Ext.isSafari2 ? 'ext-safari2' : (Ext.isSafari3 ? 'ext-safari3' : 'ext-safari4')));
365 }else if(Ext.isChrome){
366 cls.push("ext-chrome");
373 cls.push("ext-linux");
376 if(Ext.isStrict || Ext.isBorderBox){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
377 var p = bd.parentNode;
379 p.className += Ext.isStrict ? ' ext-strict' : ' ext-border-box';
382 bd.className += cls.join(' ');
387 Ext.onReady(initExtCss);
393 * @class Ext.EventObject
394 * Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject
395 * wraps the browser's native event-object normalizing cross-browser differences,
396 * such as which mouse button is clicked, keys pressed, mechanisms to stop
397 * event-propagation along with a method to prevent default actions from taking place.
398 * <p>For example:</p>
400 function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
402 var target = e.getTarget(); // same as t (the target HTMLElement)
405 var myDiv = {@link Ext#get Ext.get}("myDiv"); // get reference to an {@link Ext.Element}
406 myDiv.on( // 'on' is shorthand for addListener
407 "click", // perform an action on click of myDiv
408 handleClick // reference to the action handler
410 // other methods to do the same:
411 Ext.EventManager.on("myDiv", 'click', handleClick);
412 Ext.EventManager.addListener("myDiv", 'click', handleClick);
416 Ext.EventObject = function(){
417 var E = Ext.lib.Event,
418 // safari keypress events for special keys return bad keycodes
425 63276 : 33, // page up
426 63277 : 34, // page down
427 63272 : 46, // delete
431 // normalize button clicks
432 btnMap = Ext.isIE ? {1:0,4:1,2:2} :
433 (Ext.isWebKit ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
435 Ext.EventObjectImpl = function(e){
437 this.setEvent(e.browserEvent || e);
441 Ext.EventObjectImpl.prototype = {
443 setEvent : function(e){
445 if(e == me || (e && e.browserEvent)){ // already wrapped
451 me.button = e.button ? btnMap[e.button] : (e.which ? e.which - 1 : -1);
452 if(e.type == 'click' && me.button == -1){
456 me.shiftKey = e.shiftKey;
457 // mac metaKey behaves like ctrlKey
458 me.ctrlKey = e.ctrlKey || e.metaKey || false;
459 me.altKey = e.altKey;
460 // in getKey these will be normalized for the mac
461 me.keyCode = e.keyCode;
462 me.charCode = e.charCode;
463 // cache the target for the delayed and or buffered events
464 me.target = E.getTarget(e);
481 * Stop the event (preventDefault and stopPropagation)
483 stopEvent : function(){
486 if(me.browserEvent.type == 'mousedown'){
487 Ext.EventManager.stoppedMouseDownEvent.fire(me);
489 E.stopEvent(me.browserEvent);
494 * Prevents the browsers default handling of the event.
496 preventDefault : function(){
497 if(this.browserEvent){
498 E.preventDefault(this.browserEvent);
503 * Cancels bubbling of the event.
505 stopPropagation : function(){
508 if(me.browserEvent.type == 'mousedown'){
509 Ext.EventManager.stoppedMouseDownEvent.fire(me);
511 E.stopPropagation(me.browserEvent);
516 * Gets the character code for the event.
519 getCharCode : function(){
520 return this.charCode || this.keyCode;
524 * Returns a normalized keyCode for the event.
525 * @return {Number} The key code
528 return this.normalizeKey(this.keyCode || this.charCode)
532 normalizeKey: function(k){
533 return Ext.isSafari ? (safariKeys[k] || k) : k;
537 * Gets the x coordinate of the event.
540 getPageX : function(){
545 * Gets the y coordinate of the event.
548 getPageY : function(){
553 * Gets the page coordinates of the event.
554 * @return {Array} The xy values like [x, y]
561 * Gets the target for the event.
562 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
563 * @param {Number/Mixed} maxDepth (optional) The max depth to
564 search as a number or element (defaults to 10 || document.body)
565 * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
566 * @return {HTMLelement}
568 getTarget : function(selector, maxDepth, returnEl){
569 return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target);
573 * Gets the related target.
574 * @return {HTMLElement}
576 getRelatedTarget : function(){
577 return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null;
581 * Normalizes mouse wheel delta across browsers
582 * @return {Number} The delta
584 getWheelDelta : function(){
585 var e = this.browserEvent;
587 if(e.wheelDelta){ /* IE/Opera. */
588 delta = e.wheelDelta/120;
589 }else if(e.detail){ /* Mozilla case. */
596 * 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.
597 * Example usage:<pre><code>
598 // Handle click on any child of an element
599 Ext.getBody().on('click', function(e){
600 if(e.within('some-el')){
601 alert('Clicked on a child of some-el!');
605 // Handle click directly on an element, ignoring clicks on child nodes
606 Ext.getBody().on('click', function(e,t){
607 if((t.id == 'some-el') && !e.within(t, true)){
608 alert('Clicked directly on some-el!');
612 * @param {Mixed} el The id, DOM element or Ext.Element to check
613 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
614 * @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target
617 within : function(el, related, allowEl){
619 var t = this[related ? "getRelatedTarget" : "getTarget"]();
620 return t && ((allowEl ? (t == Ext.getDom(el)) : false) || Ext.fly(el).contains(t));
626 return new Ext.EventObjectImpl();