4 * Copyright(c) 2006-2007, Ext JS, LLC.
6 * Originally Released Under LGPL - original licence link has changed is not relivant.
9 * <script type="text/javascript">
13 * @class Roo.EventManager
14 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
15 * several useful events directly.
16 * See {@link Roo.EventObject} for more details on normalized event objects.
19 Roo.EventManager = function(){
20 var docReadyEvent, docReadyProcId, docReadyState = false;
21 var resizeEvent, resizeTask, textEvent, textSize;
22 var E = Roo.lib.Event;
26 var fireDocReady = function(){
31 clearInterval(docReadyProcId);
33 if(Roo.isGecko || Roo.isOpera) {
34 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
37 var defer = document.getElementById("ie-deferred-loader");
39 defer.onreadystatechange = null;
40 defer.parentNode.removeChild(defer);
45 docReadyEvent.clearListeners();
50 var initDocReady = function(){
51 docReadyEvent = new Roo.util.Event();
52 if(Roo.isGecko || Roo.isOpera) {
53 document.addEventListener("DOMContentLoaded", fireDocReady, false);
55 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
56 var defer = document.getElementById("ie-deferred-loader");
57 defer.onreadystatechange = function(){
58 if(this.readyState == "complete"){
62 }else if(Roo.isSafari){
63 docReadyProcId = setInterval(function(){
64 var rs = document.readyState;
65 if(rs == "complete") {
70 // no matter what, make sure it fires on load
71 E.on(window, "load", fireDocReady);
74 var createBuffered = function(h, o){
75 var task = new Roo.util.DelayedTask(h);
77 // create new event object impl so new events don't wipe out properties
78 e = new Roo.EventObjectImpl(e);
79 task.delay(o.buffer, h, null, [e]);
83 var createSingle = function(h, el, ename, fn){
85 Roo.EventManager.removeListener(el, ename, fn);
90 var createDelayed = function(h, o){
92 // create new event object impl so new events don't wipe out properties
93 e = new Roo.EventObjectImpl(e);
94 setTimeout(function(){
100 var listen = function(element, ename, opt, fn, scope){
101 var o = (!opt || typeof opt == "boolean") ? {} : opt;
102 fn = fn || o.fn; scope = scope || o.scope;
103 var el = Roo.getDom(element);
105 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
108 e = Roo.EventObject.setEvent(e);
111 t = e.getTarget(o.delegate, el);
118 if(o.stopEvent === true){
121 if(o.preventDefault === true){
124 if(o.stopPropagation === true){
128 if(o.normalized === false){
132 fn.call(scope || el, e, t, o);
135 h = createDelayed(h, o);
138 h = createSingle(h, el, ename, fn);
141 h = createBuffered(h, o);
143 fn._handlers = fn._handlers || [];
144 fn._handlers.push([Roo.id(el), ename, h]);
147 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
148 el.addEventListener("DOMMouseScroll", h, false);
149 E.on(window, 'unload', function(){
150 el.removeEventListener("DOMMouseScroll", h, false);
153 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
154 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
159 var stopListening = function(el, ename, fn){
160 var id = Roo.id(el), hds = fn._handlers, hd = fn;
162 for(var i = 0, len = hds.length; i < len; i++){
164 if(h[0] == id && h[1] == ename){
173 if(ename == "mousewheel" && el.addEventListener){
174 el.removeEventListener("DOMMouseScroll", hd, false);
176 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
177 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
181 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
188 * @scope Roo.EventManager
193 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
194 * object with a Roo.EventObject
195 * @param {Function} fn The method the event invokes
196 * @param {Object} scope An object that becomes the scope of the handler
197 * @param {boolean} override If true, the obj passed in becomes
198 * the execution scope of the listener
199 * @return {Function} The wrapped function
202 wrap : function(fn, scope, override){
204 Roo.EventObject.setEvent(e);
205 fn.call(override ? scope || window : window, Roo.EventObject, scope);
210 * Appends an event handler to an element (shorthand for addListener)
211 * @param {String/HTMLElement} element The html element or id to assign the
212 * @param {String} eventName The type of event to listen for
213 * @param {Function} handler The method the event invokes
214 * @param {Object} scope (optional) The scope in which to execute the handler
215 * function. The handler function's "this" context.
216 * @param {Object} options (optional) An object containing handler configuration
217 * properties. This may contain any of the following properties:<ul>
218 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
219 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
220 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
221 * <li>preventDefault {Boolean} True to prevent the default action</li>
222 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
223 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
224 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
225 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
226 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
227 * by the specified number of milliseconds. If the event fires again within that time, the original
228 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
231 * <b>Combining Options</b><br>
232 * Using the options argument, it is possible to combine different types of listeners:<br>
234 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
236 el.on('click', this.onClick, this, {
243 * <b>Attaching multiple handlers in 1 call</b><br>
244 * The method also allows for a single argument to be passed which is a config object containing properties
245 * which specify multiple handlers.
264 * Or a shorthand syntax:<br>
267 'click' : this.onClick,
268 'mouseover' : this.onMouseOver,
269 'mouseout' : this.onMouseOut
273 addListener : function(element, eventName, fn, scope, options){
274 if(typeof eventName == "object"){
280 if(typeof o[e] == "function"){
282 listen(element, e, o, o[e], o.scope);
284 // individual options
285 listen(element, e, o[e]);
290 return listen(element, eventName, options, fn, scope);
294 * Removes an event handler
296 * @param {String/HTMLElement} element The id or html element to remove the
298 * @param {String} eventName The type of event
299 * @param {Function} fn
300 * @return {Boolean} True if a listener was actually removed
302 removeListener : function(element, eventName, fn){
303 return stopListening(element, eventName, fn);
307 * Fires when the document is ready (before onload and before images are loaded). Can be
308 * accessed shorthanded Roo.onReady().
309 * @param {Function} fn The method the event invokes
310 * @param {Object} scope An object that becomes the scope of the handler
311 * @param {boolean} options
313 onDocumentReady : function(fn, scope, options){
314 if(docReadyState){ // if it already fired
315 docReadyEvent.addListener(fn, scope, options);
316 docReadyEvent.fire();
317 docReadyEvent.clearListeners();
323 docReadyEvent.addListener(fn, scope, options);
327 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
328 * @param {Function} fn The method the event invokes
329 * @param {Object} scope An object that becomes the scope of the handler
330 * @param {boolean} options
332 onWindowResize : function(fn, scope, options){
334 resizeEvent = new Roo.util.Event();
335 resizeTask = new Roo.util.DelayedTask(function(){
336 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
338 E.on(window, "resize", function(){
340 resizeTask.delay(50);
342 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
346 resizeEvent.addListener(fn, scope, options);
350 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
351 * @param {Function} fn The method the event invokes
352 * @param {Object} scope An object that becomes the scope of the handler
353 * @param {boolean} options
355 onTextResize : function(fn, scope, options){
357 textEvent = new Roo.util.Event();
358 var textEl = new Roo.Element(document.createElement('div'));
359 textEl.dom.className = 'x-text-resize';
360 textEl.dom.innerHTML = 'X';
361 textEl.appendTo(document.body);
362 textSize = textEl.dom.offsetHeight;
363 setInterval(function(){
364 if(textEl.dom.offsetHeight != textSize){
365 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
367 }, this.textResizeInterval);
369 textEvent.addListener(fn, scope, options);
373 * Removes the passed window resize listener.
374 * @param {Function} fn The method the event invokes
375 * @param {Object} scope The scope of handler
377 removeResizeListener : function(fn, scope){
379 resizeEvent.removeListener(fn, scope);
384 fireResize : function(){
386 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
390 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
394 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
396 textResizeInterval : 50
401 * @scopeAlias pub=Roo.EventManager
405 * Appends an event handler to an element (shorthand for addListener)
406 * @param {String/HTMLElement} element The html element or id to assign the
407 * @param {String} eventName The type of event to listen for
408 * @param {Function} handler The method the event invokes
409 * @param {Object} scope (optional) The scope in which to execute the handler
410 * function. The handler function's "this" context.
411 * @param {Object} options (optional) An object containing handler configuration
412 * properties. This may contain any of the following properties:<ul>
413 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
414 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
415 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
416 * <li>preventDefault {Boolean} True to prevent the default action</li>
417 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
418 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
419 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
420 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
421 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
422 * by the specified number of milliseconds. If the event fires again within that time, the original
423 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
426 * <b>Combining Options</b><br>
427 * Using the options argument, it is possible to combine different types of listeners:<br>
429 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
431 el.on('click', this.onClick, this, {
438 * <b>Attaching multiple handlers in 1 call</b><br>
439 * The method also allows for a single argument to be passed which is a config object containing properties
440 * which specify multiple handlers.
459 * Or a shorthand syntax:<br>
462 'click' : this.onClick,
463 'mouseover' : this.onMouseOver,
464 'mouseout' : this.onMouseOut
468 pub.on = pub.addListener;
469 pub.un = pub.removeListener;
471 pub.stoppedMouseDownEvent = new Roo.util.Event();
475 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
476 * @param {Function} fn The method the event invokes
477 * @param {Object} scope An object that becomes the scope of the handler
478 * @param {boolean} override If true, the obj passed in becomes
479 * the execution scope of the listener
483 Roo.onReady = Roo.EventManager.onDocumentReady;
485 Roo.onReady(function(){
486 var bd = Roo.get(document.body);
491 : Roo.isGecko ? "roo-gecko"
492 : Roo.isOpera ? "roo-opera"
493 : Roo.isSafari ? "roo-safari" : ""];
499 cls.push("roo-linux");
502 cls.push('roo-border-box');
504 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
505 var p = bd.dom.parentNode;
507 p.className += ' roo-strict';
510 bd.addClass(cls.join(' '));
514 * @class Roo.EventObject
515 * EventObject exposes the Yahoo! UI Event functionality directly on the object
516 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
519 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
521 var target = e.getTarget();
524 var myDiv = Roo.get("myDiv");
525 myDiv.on("click", handleClick);
527 Roo.EventManager.on("myDiv", 'click', handleClick);
528 Roo.EventManager.addListener("myDiv", 'click', handleClick);
532 Roo.EventObject = function(){
534 var E = Roo.lib.Event;
536 // safari keypress events for special keys return bad keycodes
542 63276 : 33, // page up
543 63277 : 34, // page down
544 63272 : 46, // delete
549 // normalize button clicks
550 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
551 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
553 Roo.EventObjectImpl = function(e){
555 this.setEvent(e.browserEvent || e);
558 Roo.EventObjectImpl.prototype = {
560 * Used to fix doc tools.
561 * @scope Roo.EventObject.prototype
567 /** The normal browser event */
569 /** The button pressed in a mouse event */
571 /** True if the shift key was down during the event */
573 /** True if the control key was down during the event */
575 /** True if the alt key was down during the event */
634 setEvent : function(e){
635 if(e == this || (e && e.browserEvent)){ // already wrapped
638 this.browserEvent = e;
641 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
642 if(e.type == 'click' && this.button == -1){
646 this.shiftKey = e.shiftKey;
647 // mac metaKey behaves like ctrlKey
648 this.ctrlKey = e.ctrlKey || e.metaKey;
649 this.altKey = e.altKey;
650 // in getKey these will be normalized for the mac
651 this.keyCode = e.keyCode;
652 // keyup warnings on firefox.
653 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
654 // cache the target for the delayed and or buffered events
655 this.target = E.getTarget(e);
657 this.xy = E.getXY(e);
660 this.shiftKey = false;
661 this.ctrlKey = false;
672 * Stop the event (preventDefault and stopPropagation)
674 stopEvent : function(){
675 if(this.browserEvent){
676 if(this.browserEvent.type == 'mousedown'){
677 Roo.EventManager.stoppedMouseDownEvent.fire(this);
679 E.stopEvent(this.browserEvent);
684 * Prevents the browsers default handling of the event.
686 preventDefault : function(){
687 if(this.browserEvent){
688 E.preventDefault(this.browserEvent);
693 isNavKeyPress : function(){
694 var k = this.keyCode;
695 k = Roo.isSafari ? (safariKeys[k] || k) : k;
696 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
699 isSpecialKey : function(){
700 var k = this.keyCode;
701 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
702 (k == 16) || (k == 17) ||
703 (k >= 18 && k <= 20) ||
704 (k >= 33 && k <= 35) ||
705 (k >= 36 && k <= 39) ||
706 (k >= 44 && k <= 45);
709 * Cancels bubbling of the event.
711 stopPropagation : function(){
712 if(this.browserEvent){
713 if(this.type == 'mousedown'){
714 Roo.EventManager.stoppedMouseDownEvent.fire(this);
716 E.stopPropagation(this.browserEvent);
721 * Gets the key code for the event.
724 getCharCode : function(){
725 return this.charCode || this.keyCode;
729 * Returns a normalized keyCode for the event.
730 * @return {Number} The key code
733 var k = this.keyCode || this.charCode;
734 return Roo.isSafari ? (safariKeys[k] || k) : k;
738 * Gets the x coordinate of the event.
741 getPageX : function(){
746 * Gets the y coordinate of the event.
749 getPageY : function(){
754 * Gets the time of the event.
757 getTime : function(){
758 if(this.browserEvent){
759 return E.getTime(this.browserEvent);
765 * Gets the page coordinates of the event.
766 * @return {Array} The xy values like [x, y]
773 * Gets the target for the event.
774 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
775 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
776 search as a number or element (defaults to 10 || document.body)
777 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
778 * @return {HTMLelement}
780 getTarget : function(selector, maxDepth, returnEl){
781 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
784 * Gets the related target.
785 * @return {HTMLElement}
787 getRelatedTarget : function(){
788 if(this.browserEvent){
789 return E.getRelatedTarget(this.browserEvent);
795 * Normalizes mouse wheel delta across browsers
796 * @return {Number} The delta
798 getWheelDelta : function(){
799 var e = this.browserEvent;
801 if(e.wheelDelta){ /* IE/Opera. */
802 delta = e.wheelDelta/120;
803 }else if(e.detail){ /* Mozilla case. */
810 * Returns true if the control, meta, shift or alt key was pressed during this event.
813 hasModifier : function(){
814 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
818 * Returns true if the target of this event equals el or is a child of el
819 * @param {String/HTMLElement/Element} el
820 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
823 within : function(el, related){
824 var t = this[related ? "getRelatedTarget" : "getTarget"]();
825 return t && Roo.fly(el).contains(t);
828 getPoint : function(){
829 return new Roo.lib.Point(this.xy[0], this.xy[1]);
833 return new Roo.EventObjectImpl();