MDL-10604:
[moodle-linuxchix.git] / lib / yui / event / event-debug.js
blob468e592e718bb72625e5a1c4a23c53c453ec3111
1 /*
2 Copyright (c) 2006, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
5 version: 0.12.2
6 */
9 /**
10 * The CustomEvent class lets you define events for your application
11 * that can be subscribed to by one or more independent component.
13 * @param {String} type The type of event, which is passed to the callback
14 * when the event fires
15 * @param {Object} oScope The context the event will fire from. "this" will
16 * refer to this object in the callback. Default value:
17 * the window object. The listener can override this.
18 * @param {boolean} silent pass true to prevent the event from writing to
19 * the debugsystem
20 * @param {int} signature the signature that the custom event subscriber
21 * will receive. YAHOO.util.CustomEvent.LIST or
22 * YAHOO.util.CustomEvent.FLAT. The default is
23 * YAHOO.util.CustomEvent.LIST.
24 * @namespace YAHOO.util
25 * @class CustomEvent
26 * @constructor
28 YAHOO.util.CustomEvent = function(type, oScope, silent, signature) {
30 /**
31 * The type of event, returned to subscribers when the event fires
32 * @property type
33 * @type string
35 this.type = type;
37 /**
38 * The scope the the event will fire from by default. Defaults to the window
39 * obj
40 * @property scope
41 * @type object
43 this.scope = oScope || window;
45 /**
46 * By default all custom events are logged in the debug build, set silent
47 * to true to disable debug outpu for this event.
48 * @property silent
49 * @type boolean
51 this.silent = silent;
53 /**
54 * Custom events support two styles of arguments provided to the event
55 * subscribers.
56 * <ul>
57 * <li>YAHOO.util.CustomEvent.LIST:
58 * <ul>
59 * <li>param1: event name</li>
60 * <li>param2: array of arguments sent to fire</li>
61 * <li>param3: <optional> a custom object supplied by the subscriber</li>
62 * </ul>
63 * </li>
64 * <li>YAHOO.util.CustomEvent.FLAT
65 * <ul>
66 * <li>param1: the first argument passed to fire. If you need to
67 * pass multiple parameters, use and array or object literal</li>
68 * <li>param2: <optional> a custom object supplied by the subscriber</li>
69 * </ul>
70 * </li>
71 * </ul>
72 * @property signature
73 * @type int
75 this.signature = signature || YAHOO.util.CustomEvent.LIST;
77 /**
78 * The subscribers to this event
79 * @property subscribers
80 * @type Subscriber[]
82 this.subscribers = [];
84 if (!this.silent) {
85 YAHOO.log( "Creating " + this, "info", "Event" );
88 var onsubscribeType = "_YUICEOnSubscribe";
90 // Only add subscribe events for events that are not generated by
91 // CustomEvent
92 if (type !== onsubscribeType) {
94 /**
95 * Custom events provide a custom event that fires whenever there is
96 * a new subscriber to the event. This provides an opportunity to
97 * handle the case where there is a non-repeating event that has
98 * already fired has a new subscriber.
100 * @event subscribeEvent
101 * @type YAHOO.util.CustomEvent
102 * @param {Function} fn The function to execute
103 * @param {Object} obj An object to be passed along when the event
104 * fires
105 * @param {boolean|Object} override If true, the obj passed in becomes
106 * the execution scope of the listener.
107 * if an object, that object becomes the
108 * the execution scope.
110 this.subscribeEvent =
111 new YAHOO.util.CustomEvent(onsubscribeType, this, true);
117 * Subscriber listener sigature constant. The LIST type returns three
118 * parameters: the event type, the array of args passed to fire, and
119 * the optional custom object
120 * @property YAHOO.util.CustomEvent.LIST
121 * @static
122 * @type int
124 YAHOO.util.CustomEvent.LIST = 0;
127 * Subscriber listener sigature constant. The FLAT type returns two
128 * parameters: the first argument passed to fire and the optional
129 * custom object
130 * @property YAHOO.util.CustomEvent.FLAT
131 * @static
132 * @type int
134 YAHOO.util.CustomEvent.FLAT = 1;
136 YAHOO.util.CustomEvent.prototype = {
139 * Subscribes the caller to this event
140 * @method subscribe
141 * @param {Function} fn The function to execute
142 * @param {Object} obj An object to be passed along when the event
143 * fires
144 * @param {boolean|Object} override If true, the obj passed in becomes
145 * the execution scope of the listener.
146 * if an object, that object becomes the
147 * the execution scope.
149 subscribe: function(fn, obj, override) {
150 if (this.subscribeEvent) {
151 this.subscribeEvent.fire(fn, obj, override);
154 this.subscribers.push( new YAHOO.util.Subscriber(fn, obj, override) );
158 * Unsubscribes the caller from this event
159 * @method unsubscribe
160 * @param {Function} fn The function to execute
161 * @param {Object} obj The custom object passed to subscribe (optional)
162 * @return {boolean} True if the subscriber was found and detached.
164 unsubscribe: function(fn, obj) {
165 var found = false;
166 for (var i=0, len=this.subscribers.length; i<len; ++i) {
167 var s = this.subscribers[i];
168 if (s && s.contains(fn, obj)) {
169 this._delete(i);
170 found = true;
174 return found;
178 * Notifies the subscribers. The callback functions will be executed
179 * from the scope specified when the event was created, and with the
180 * following parameters:
181 * <ul>
182 * <li>The type of event</li>
183 * <li>All of the arguments fire() was executed with as an array</li>
184 * <li>The custom object (if any) that was passed into the subscribe()
185 * method</li>
186 * </ul>
187 * @method fire
188 * @param {Object*} arguments an arbitrary set of parameters to pass to
189 * the handler.
190 * @return {boolean} false if one of the subscribers returned false,
191 * true otherwise
193 fire: function() {
194 var len=this.subscribers.length;
195 if (!len && this.silent) {
196 return true;
199 var args=[], ret=true, i;
201 for (i=0; i<arguments.length; ++i) {
202 args.push(arguments[i]);
205 var argslength = args.length;
207 if (!this.silent) {
208 YAHOO.log( "Firing " + this + ", " +
209 "args: " + args + ", " +
210 "subscribers: " + len,
211 "info", "Event" );
214 for (i=0; i<len; ++i) {
215 var s = this.subscribers[i];
216 if (s) {
217 if (!this.silent) {
218 YAHOO.log( this.type + "->" + (i+1) + ": " + s,
219 "info", "Event" );
222 var scope = s.getScope(this.scope);
224 if (this.signature == YAHOO.util.CustomEvent.FLAT) {
225 var param = null;
226 if (args.length > 0) {
227 param = args[0];
229 ret = s.fn.call(scope, param, s.obj);
230 } else {
231 ret = s.fn.call(scope, this.type, args, s.obj);
233 if (false === ret) {
234 if (!this.silent) {
235 YAHOO.log("Event cancelled, subscriber " + i +
236 " of " + len);
239 //break;
240 return false;
245 return true;
249 * Removes all listeners
250 * @method unsubscribeAll
252 unsubscribeAll: function() {
253 for (var i=0, len=this.subscribers.length; i<len; ++i) {
254 this._delete(len - 1 - i);
259 * @method _delete
260 * @private
262 _delete: function(index) {
263 var s = this.subscribers[index];
264 if (s) {
265 delete s.fn;
266 delete s.obj;
269 // delete this.subscribers[index];
270 this.subscribers.splice(index, 1);
274 * @method toString
276 toString: function() {
277 return "CustomEvent: " + "'" + this.type + "', " +
278 "scope: " + this.scope;
283 /////////////////////////////////////////////////////////////////////
286 * Stores the subscriber information to be used when the event fires.
287 * @param {Function} fn The function to execute
288 * @param {Object} obj An object to be passed along when the event fires
289 * @param {boolean} override If true, the obj passed in becomes the execution
290 * scope of the listener
291 * @class Subscriber
292 * @constructor
294 YAHOO.util.Subscriber = function(fn, obj, override) {
297 * The callback that will be execute when the event fires
298 * @property fn
299 * @type function
301 this.fn = fn;
304 * An optional custom object that will passed to the callback when
305 * the event fires
306 * @property obj
307 * @type object
309 this.obj = obj || null;
312 * The default execution scope for the event listener is defined when the
313 * event is created (usually the object which contains the event).
314 * By setting override to true, the execution scope becomes the custom
315 * object passed in by the subscriber. If override is an object, that
316 * object becomes the scope.
317 * @property override
318 * @type boolean|object
320 this.override = override;
325 * Returns the execution scope for this listener. If override was set to true
326 * the custom obj will be the scope. If override is an object, that is the
327 * scope, otherwise the default scope will be used.
328 * @method getScope
329 * @param {Object} defaultScope the scope to use if this listener does not
330 * override it.
332 YAHOO.util.Subscriber.prototype.getScope = function(defaultScope) {
333 if (this.override) {
334 if (this.override === true) {
335 return this.obj;
336 } else {
337 return this.override;
340 return defaultScope;
344 * Returns true if the fn and obj match this objects properties.
345 * Used by the unsubscribe method to match the right subscriber.
347 * @method contains
348 * @param {Function} fn the function to execute
349 * @param {Object} obj an object to be passed along when the event fires
350 * @return {boolean} true if the supplied arguments match this
351 * subscriber's signature.
353 YAHOO.util.Subscriber.prototype.contains = function(fn, obj) {
354 if (obj) {
355 return (this.fn == fn && this.obj == obj);
356 } else {
357 return (this.fn == fn);
362 * @method toString
364 YAHOO.util.Subscriber.prototype.toString = function() {
365 return "Subscriber { obj: " + (this.obj || "") +
366 ", override: " + (this.override || "no") + " }";
370 * The Event Utility provides utilities for managing DOM Events and tools
371 * for building event systems
373 * @module event
374 * @title Event Utility
375 * @namespace YAHOO.util
376 * @requires yahoo
379 // The first instance of Event will win if it is loaded more than once.
380 if (!YAHOO.util.Event) {
383 * The event utility provides functions to add and remove event listeners,
384 * event cleansing. It also tries to automatically remove listeners it
385 * registers during the unload event.
387 * @class Event
388 * @static
390 YAHOO.util.Event = function() {
393 * True after the onload event has fired
394 * @property loadComplete
395 * @type boolean
396 * @static
397 * @private
399 var loadComplete = false;
402 * Cache of wrapped listeners
403 * @property listeners
404 * @type array
405 * @static
406 * @private
408 var listeners = [];
411 * User-defined unload function that will be fired before all events
412 * are detached
413 * @property unloadListeners
414 * @type array
415 * @static
416 * @private
418 var unloadListeners = [];
421 * Cache of DOM0 event handlers to work around issues with DOM2 events
422 * in Safari
423 * @property legacyEvents
424 * @static
425 * @private
427 var legacyEvents = [];
430 * Listener stack for DOM0 events
431 * @property legacyHandlers
432 * @static
433 * @private
435 var legacyHandlers = [];
438 * The number of times to poll after window.onload. This number is
439 * increased if additional late-bound handlers are requested after
440 * the page load.
441 * @property retryCount
442 * @static
443 * @private
445 var retryCount = 0;
448 * onAvailable listeners
449 * @property onAvailStack
450 * @static
451 * @private
453 var onAvailStack = [];
456 * Lookup table for legacy events
457 * @property legacyMap
458 * @static
459 * @private
461 var legacyMap = [];
464 * Counter for auto id generation
465 * @property counter
466 * @static
467 * @private
469 var counter = 0;
471 return { // PREPROCESS
474 * The number of times we should look for elements that are not
475 * in the DOM at the time the event is requested after the document
476 * has been loaded. The default is 200@amp;50 ms, so it will poll
477 * for 10 seconds or until all outstanding handlers are bound
478 * (whichever comes first).
479 * @property POLL_RETRYS
480 * @type int
481 * @static
482 * @final
484 POLL_RETRYS: 200,
487 * The poll interval in milliseconds
488 * @property POLL_INTERVAL
489 * @type int
490 * @static
491 * @final
493 POLL_INTERVAL: 20,
496 * Element to bind, int constant
497 * @property EL
498 * @type int
499 * @static
500 * @final
502 EL: 0,
505 * Type of event, int constant
506 * @property TYPE
507 * @type int
508 * @static
509 * @final
511 TYPE: 1,
514 * Function to execute, int constant
515 * @property FN
516 * @type int
517 * @static
518 * @final
520 FN: 2,
523 * Function wrapped for scope correction and cleanup, int constant
524 * @property WFN
525 * @type int
526 * @static
527 * @final
529 WFN: 3,
532 * Object passed in by the user that will be returned as a
533 * parameter to the callback, int constant
534 * @property OBJ
535 * @type int
536 * @static
537 * @final
539 OBJ: 3,
542 * Adjusted scope, either the element we are registering the event
543 * on or the custom object passed in by the listener, int constant
544 * @property ADJ_SCOPE
545 * @type int
546 * @static
547 * @final
549 ADJ_SCOPE: 4,
552 * Safari detection is necessary to work around the preventDefault
553 * bug that makes it so you can't cancel a href click from the
554 * handler. There is not a capabilities check we can use here.
555 * @property isSafari
556 * @private
557 * @static
559 isSafari: (/Safari|Konqueror|KHTML/gi).test(navigator.userAgent),
562 * IE detection needed to properly calculate pageX and pageY.
563 * capabilities checking didn't seem to work because another
564 * browser that does not provide the properties have the values
565 * calculated in a different manner than IE.
566 * @property isIE
567 * @private
568 * @static
570 isIE: (!this.isSafari && !navigator.userAgent.match(/opera/gi) &&
571 navigator.userAgent.match(/msie/gi)),
574 * poll handle
575 * @property _interval
576 * @private
578 _interval: null,
581 * @method startInterval
582 * @static
583 * @private
585 startInterval: function() {
586 if (!this._interval) {
587 var self = this;
588 var callback = function() { self._tryPreloadAttach(); };
589 this._interval = setInterval(callback, this.POLL_INTERVAL);
590 // this.timeout = setTimeout(callback, i);
595 * Executes the supplied callback when the item with the supplied
596 * id is found. This is meant to be used to execute behavior as
597 * soon as possible as the page loads. If you use this after the
598 * initial page load it will poll for a fixed time for the element.
599 * The number of times it will poll and the frequency are
600 * configurable. By default it will poll for 10 seconds.
602 * @method onAvailable
604 * @param {string} p_id the id of the element to look for.
605 * @param {function} p_fn what to execute when the element is found.
606 * @param {object} p_obj an optional object to be passed back as
607 * a parameter to p_fn.
608 * @param {boolean} p_override If set to true, p_fn will execute
609 * in the scope of p_obj
611 * @static
613 onAvailable: function(p_id, p_fn, p_obj, p_override) {
614 onAvailStack.push( { id: p_id,
615 fn: p_fn,
616 obj: p_obj,
617 override: p_override,
618 checkReady: false } );
620 retryCount = this.POLL_RETRYS;
621 this.startInterval();
625 * Works the same way as onAvailable, but additionally checks the
626 * state of sibling elements to determine if the content of the
627 * available element is safe to modify.
629 * @method onContentReady
631 * @param {string} p_id the id of the element to look for.
632 * @param {function} p_fn what to execute when the element is ready.
633 * @param {object} p_obj an optional object to be passed back as
634 * a parameter to p_fn.
635 * @param {boolean} p_override If set to true, p_fn will execute
636 * in the scope of p_obj
638 * @static
640 onContentReady: function(p_id, p_fn, p_obj, p_override) {
641 onAvailStack.push( { id: p_id,
642 fn: p_fn,
643 obj: p_obj,
644 override: p_override,
645 checkReady: true } );
647 retryCount = this.POLL_RETRYS;
648 this.startInterval();
652 * Appends an event handler
654 * @method addListener
656 * @param {Object} el The html element to assign the
657 * event to
658 * @param {String} sType The type of event to append
659 * @param {Function} fn The method the event invokes
660 * @param {Object} obj An arbitrary object that will be
661 * passed as a parameter to the handler
662 * @param {boolean} override If true, the obj passed in becomes
663 * the execution scope of the listener
664 * @return {boolean} True if the action was successful or defered,
665 * false if one or more of the elements
666 * could not have the listener attached,
667 * or if the operation throws an exception.
668 * @static
670 addListener: function(el, sType, fn, obj, override) {
673 if (!fn || !fn.call) {
674 // this.logger.debug("Error, function is not valid " + fn);
675 return false;
678 // The el argument can be an array of elements or element ids.
679 if ( this._isValidCollection(el)) {
680 var ok = true;
681 for (var i=0,len=el.length; i<len; ++i) {
682 ok = this.on(el[i],
683 sType,
684 fn,
685 obj,
686 override) && ok;
688 return ok;
690 } else if (typeof el == "string") {
691 var oEl = this.getEl(el);
692 // If the el argument is a string, we assume it is
693 // actually the id of the element. If the page is loaded
694 // we convert el to the actual element, otherwise we
695 // defer attaching the event until onload event fires
697 // check to see if we need to delay hooking up the event
698 // until after the page loads.
699 if (oEl) {
700 el = oEl;
701 } else {
702 // defer adding the event until the element is available
703 this.onAvailable(el, function() {
704 YAHOO.util.Event.on(el, sType, fn, obj, override);
707 return true;
711 // Element should be an html element or an array if we get
712 // here.
713 if (!el) {
714 // this.logger.debug("unable to attach event " + sType);
715 return false;
718 // we need to make sure we fire registered unload events
719 // prior to automatically unhooking them. So we hang on to
720 // these instead of attaching them to the window and fire the
721 // handles explicitly during our one unload event.
722 if ("unload" == sType && obj !== this) {
723 unloadListeners[unloadListeners.length] =
724 [el, sType, fn, obj, override];
725 return true;
728 // this.logger.debug("Adding handler: " + el + ", " + sType);
730 // if the user chooses to override the scope, we use the custom
731 // object passed in, otherwise the executing scope will be the
732 // HTML element that the event is registered on
733 var scope = el;
734 if (override) {
735 if (override === true) {
736 scope = obj;
737 } else {
738 scope = override;
742 // wrap the function so we can return the obj object when
743 // the event fires;
744 var wrappedFn = function(e) {
745 return fn.call(scope, YAHOO.util.Event.getEvent(e),
746 obj);
749 var li = [el, sType, fn, wrappedFn, scope];
750 var index = listeners.length;
751 // cache the listener so we can try to automatically unload
752 listeners[index] = li;
754 if (this.useLegacyEvent(el, sType)) {
755 var legacyIndex = this.getLegacyIndex(el, sType);
757 // Add a new dom0 wrapper if one is not detected for this
758 // element
759 if ( legacyIndex == -1 ||
760 el != legacyEvents[legacyIndex][0] ) {
762 legacyIndex = legacyEvents.length;
763 legacyMap[el.id + sType] = legacyIndex;
765 // cache the signature for the DOM0 event, and
766 // include the existing handler for the event, if any
767 legacyEvents[legacyIndex] =
768 [el, sType, el["on" + sType]];
769 legacyHandlers[legacyIndex] = [];
771 el["on" + sType] =
772 function(e) {
773 YAHOO.util.Event.fireLegacyEvent(
774 YAHOO.util.Event.getEvent(e), legacyIndex);
778 // add a reference to the wrapped listener to our custom
779 // stack of events
780 //legacyHandlers[legacyIndex].push(index);
781 legacyHandlers[legacyIndex].push(li);
783 } else {
784 try {
785 this._simpleAdd(el, sType, wrappedFn, false);
786 } catch(e) {
787 // handle an error trying to attach an event. If it fails
788 // we need to clean up the cache
789 this.removeListener(el, sType, fn);
790 return false;
794 return true;
799 * When using legacy events, the handler is routed to this object
800 * so we can fire our custom listener stack.
801 * @method fireLegacyEvent
802 * @static
803 * @private
805 fireLegacyEvent: function(e, legacyIndex) {
806 // this.logger.debug("fireLegacyEvent " + legacyIndex);
807 var ok = true;
809 var le = legacyHandlers[legacyIndex];
810 for (var i=0,len=le.length; i<len; ++i) {
811 var li = le[i];
812 if ( li && li[this.WFN] ) {
813 var scope = li[this.ADJ_SCOPE];
814 var ret = li[this.WFN].call(scope, e);
815 ok = (ok && ret);
819 return ok;
823 * Returns the legacy event index that matches the supplied
824 * signature
825 * @method getLegacyIndex
826 * @static
827 * @private
829 getLegacyIndex: function(el, sType) {
830 var key = this.generateId(el) + sType;
831 if (typeof legacyMap[key] == "undefined") {
832 return -1;
833 } else {
834 return legacyMap[key];
839 * Logic that determines when we should automatically use legacy
840 * events instead of DOM2 events.
841 * @method useLegacyEvent
842 * @static
843 * @private
845 useLegacyEvent: function(el, sType) {
846 if (!el.addEventListener && !el.attachEvent) {
847 return true;
848 } else if (this.isSafari) {
849 if ("click" == sType || "dblclick" == sType) {
850 return true;
853 return false;
857 * Removes an event handler
859 * @method removeListener
861 * @param {Object} el the html element or the id of the element to
862 * assign the event to.
863 * @param {String} sType the type of event to remove.
864 * @param {Function} fn the method the event invokes. If fn is
865 * undefined, then all event handlers for the type of event are
866 * removed.
867 * @return {boolean} true if the unbind was successful, false
868 * otherwise.
869 * @static
871 removeListener: function(el, sType, fn) {
872 var i, len;
874 // The el argument can be a string
875 if (typeof el == "string") {
876 el = this.getEl(el);
877 // The el argument can be an array of elements or element ids.
878 } else if ( this._isValidCollection(el)) {
879 var ok = true;
880 for (i=0,len=el.length; i<len; ++i) {
881 ok = ( this.removeListener(el[i], sType, fn) && ok );
883 return ok;
886 if (!fn || !fn.call) {
887 // this.logger.debug("Error, function is not valid " + fn);
888 //return false;
889 return this.purgeElement(el, false, sType);
893 if ("unload" == sType) {
895 for (i=0, len=unloadListeners.length; i<len; i++) {
896 var li = unloadListeners[i];
897 if (li &&
898 li[0] == el &&
899 li[1] == sType &&
900 li[2] == fn) {
901 unloadListeners.splice(i, 1);
902 return true;
906 return false;
909 var cacheItem = null;
911 // The index is a hidden parameter; needed to remove it from
912 // the method signature because it was tempting users to
913 // try and take advantage of it, which is not possible.
914 var index = arguments[3];
916 if ("undefined" == typeof index) {
917 index = this._getCacheIndex(el, sType, fn);
920 if (index >= 0) {
921 cacheItem = listeners[index];
924 if (!el || !cacheItem) {
925 // this.logger.debug("cached listener not found");
926 return false;
929 // this.logger.debug("Removing handler: " + el + ", " + sType);
931 if (this.useLegacyEvent(el, sType)) {
932 var legacyIndex = this.getLegacyIndex(el, sType);
933 var llist = legacyHandlers[legacyIndex];
934 if (llist) {
935 for (i=0, len=llist.length; i<len; ++i) {
936 li = llist[i];
937 if (li &&
938 li[this.EL] == el &&
939 li[this.TYPE] == sType &&
940 li[this.FN] == fn) {
941 llist.splice(i, 1);
942 break;
947 } else {
948 try {
949 this._simpleRemove(el, sType, cacheItem[this.WFN], false);
950 } catch(e) {
951 return false;
955 // removed the wrapped handler
956 delete listeners[index][this.WFN];
957 delete listeners[index][this.FN];
958 listeners.splice(index, 1);
960 return true;
965 * Returns the event's target element
966 * @method getTarget
967 * @param {Event} ev the event
968 * @param {boolean} resolveTextNode when set to true the target's
969 * parent will be returned if the target is a
970 * text node. @deprecated, the text node is
971 * now resolved automatically
972 * @return {HTMLElement} the event's target
973 * @static
975 getTarget: function(ev, resolveTextNode) {
976 var t = ev.target || ev.srcElement;
977 return this.resolveTextNode(t);
981 * In some cases, some browsers will return a text node inside
982 * the actual element that was targeted. This normalizes the
983 * return value for getTarget and getRelatedTarget.
984 * @method resolveTextNode
985 * @param {HTMLElement} node node to resolve
986 * @return {HTMLElement} the normized node
987 * @static
989 resolveTextNode: function(node) {
990 // if (node && node.nodeName &&
991 // "#TEXT" == node.nodeName.toUpperCase()) {
992 if (node && 3 == node.nodeType) {
993 return node.parentNode;
994 } else {
995 return node;
1000 * Returns the event's pageX
1001 * @method getPageX
1002 * @param {Event} ev the event
1003 * @return {int} the event's pageX
1004 * @static
1006 getPageX: function(ev) {
1007 var x = ev.pageX;
1008 if (!x && 0 !== x) {
1009 x = ev.clientX || 0;
1011 if ( this.isIE ) {
1012 x += this._getScrollLeft();
1016 return x;
1020 * Returns the event's pageY
1021 * @method getPageY
1022 * @param {Event} ev the event
1023 * @return {int} the event's pageY
1024 * @static
1026 getPageY: function(ev) {
1027 var y = ev.pageY;
1028 if (!y && 0 !== y) {
1029 y = ev.clientY || 0;
1031 if ( this.isIE ) {
1032 y += this._getScrollTop();
1037 return y;
1041 * Returns the pageX and pageY properties as an indexed array.
1042 * @method getXY
1043 * @param {Event} ev the event
1044 * @return {[x, y]} the pageX and pageY properties of the event
1045 * @static
1047 getXY: function(ev) {
1048 return [this.getPageX(ev), this.getPageY(ev)];
1052 * Returns the event's related target
1053 * @method getRelatedTarget
1054 * @param {Event} ev the event
1055 * @return {HTMLElement} the event's relatedTarget
1056 * @static
1058 getRelatedTarget: function(ev) {
1059 var t = ev.relatedTarget;
1060 if (!t) {
1061 if (ev.type == "mouseout") {
1062 t = ev.toElement;
1063 } else if (ev.type == "mouseover") {
1064 t = ev.fromElement;
1068 return this.resolveTextNode(t);
1072 * Returns the time of the event. If the time is not included, the
1073 * event is modified using the current time.
1074 * @method getTime
1075 * @param {Event} ev the event
1076 * @return {Date} the time of the event
1077 * @static
1079 getTime: function(ev) {
1080 if (!ev.time) {
1081 var t = new Date().getTime();
1082 try {
1083 ev.time = t;
1084 } catch(e) {
1085 return t;
1089 return ev.time;
1093 * Convenience method for stopPropagation + preventDefault
1094 * @method stopEvent
1095 * @param {Event} ev the event
1096 * @static
1098 stopEvent: function(ev) {
1099 this.stopPropagation(ev);
1100 this.preventDefault(ev);
1104 * Stops event propagation
1105 * @method stopPropagation
1106 * @param {Event} ev the event
1107 * @static
1109 stopPropagation: function(ev) {
1110 if (ev.stopPropagation) {
1111 ev.stopPropagation();
1112 } else {
1113 ev.cancelBubble = true;
1118 * Prevents the default behavior of the event
1119 * @method preventDefault
1120 * @param {Event} ev the event
1121 * @static
1123 preventDefault: function(ev) {
1124 if (ev.preventDefault) {
1125 ev.preventDefault();
1126 } else {
1127 ev.returnValue = false;
1132 * Finds the event in the window object, the caller's arguments, or
1133 * in the arguments of another method in the callstack. This is
1134 * executed automatically for events registered through the event
1135 * manager, so the implementer should not normally need to execute
1136 * this function at all.
1137 * @method getEvent
1138 * @param {Event} e the event parameter from the handler
1139 * @return {Event} the event
1140 * @static
1142 getEvent: function(e) {
1143 var ev = e || window.event;
1145 if (!ev) {
1146 var c = this.getEvent.caller;
1147 while (c) {
1148 ev = c.arguments[0];
1149 if (ev && Event == ev.constructor) {
1150 break;
1152 c = c.caller;
1156 return ev;
1160 * Returns the charcode for an event
1161 * @method getCharCode
1162 * @param {Event} ev the event
1163 * @return {int} the event's charCode
1164 * @static
1166 getCharCode: function(ev) {
1167 return ev.charCode || ev.keyCode || 0;
1171 * Locating the saved event handler data by function ref
1173 * @method _getCacheIndex
1174 * @static
1175 * @private
1177 _getCacheIndex: function(el, sType, fn) {
1178 for (var i=0,len=listeners.length; i<len; ++i) {
1179 var li = listeners[i];
1180 if ( li &&
1181 li[this.FN] == fn &&
1182 li[this.EL] == el &&
1183 li[this.TYPE] == sType ) {
1184 return i;
1188 return -1;
1192 * Generates an unique ID for the element if it does not already
1193 * have one.
1194 * @method generateId
1195 * @param el the element to create the id for
1196 * @return {string} the resulting id of the element
1197 * @static
1199 generateId: function(el) {
1200 var id = el.id;
1202 if (!id) {
1203 id = "yuievtautoid-" + counter;
1204 ++counter;
1205 el.id = id;
1208 return id;
1213 * We want to be able to use getElementsByTagName as a collection
1214 * to attach a group of events to. Unfortunately, different
1215 * browsers return different types of collections. This function
1216 * tests to determine if the object is array-like. It will also
1217 * fail if the object is an array, but is empty.
1218 * @method _isValidCollection
1219 * @param o the object to test
1220 * @return {boolean} true if the object is array-like and populated
1221 * @static
1222 * @private
1224 _isValidCollection: function(o) {
1225 // this.logger.debug(o.constructor.toString())
1226 // this.logger.debug(typeof o)
1228 return ( o && // o is something
1229 o.length && // o is indexed
1230 typeof o != "string" && // o is not a string
1231 !o.tagName && // o is not an HTML element
1232 !o.alert && // o is not a window
1233 typeof o[0] != "undefined" );
1238 * @private
1239 * @property elCache
1240 * DOM element cache
1241 * @static
1243 elCache: {},
1246 * We cache elements bound by id because when the unload event
1247 * fires, we can no longer use document.getElementById
1248 * @method getEl
1249 * @static
1250 * @private
1252 getEl: function(id) {
1253 return document.getElementById(id);
1257 * Clears the element cache
1258 * @deprecated Elements are not cached any longer
1259 * @method clearCache
1260 * @static
1261 * @private
1263 clearCache: function() { },
1266 * hook up any deferred listeners
1267 * @method _load
1268 * @static
1269 * @private
1271 _load: function(e) {
1272 loadComplete = true;
1273 var EU = YAHOO.util.Event;
1274 // Remove the listener to assist with the IE memory issue, but not
1275 // for other browsers because FF 1.0x does not like it.
1276 if (this.isIE) {
1277 EU._simpleRemove(window, "load", EU._load);
1282 * Polling function that runs before the onload event fires,
1283 * attempting to attach to DOM Nodes as soon as they are
1284 * available
1285 * @method _tryPreloadAttach
1286 * @static
1287 * @private
1289 _tryPreloadAttach: function() {
1291 if (this.locked) {
1292 return false;
1295 this.locked = true;
1297 // this.logger.debug("tryPreloadAttach");
1299 // keep trying until after the page is loaded. We need to
1300 // check the page load state prior to trying to bind the
1301 // elements so that we can be certain all elements have been
1302 // tested appropriately
1303 var tryAgain = !loadComplete;
1304 if (!tryAgain) {
1305 tryAgain = (retryCount > 0);
1308 // onAvailable
1309 var notAvail = [];
1310 for (var i=0,len=onAvailStack.length; i<len ; ++i) {
1311 var item = onAvailStack[i];
1312 if (item) {
1313 var el = this.getEl(item.id);
1315 if (el) {
1316 // The element is available, but not necessarily ready
1317 // @todo verify IE7 compatibility
1318 // @todo should we test parentNode.nextSibling?
1319 // @todo re-evaluate global content ready
1320 if ( !item.checkReady ||
1321 loadComplete ||
1322 el.nextSibling ||
1323 (document && document.body) ) {
1325 var scope = el;
1326 if (item.override) {
1327 if (item.override === true) {
1328 scope = item.obj;
1329 } else {
1330 scope = item.override;
1333 item.fn.call(scope, item.obj);
1334 //delete onAvailStack[i];
1335 // null out instead of delete for Opera
1336 onAvailStack[i] = null;
1338 } else {
1339 notAvail.push(item);
1344 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
1346 if (tryAgain) {
1347 // we may need to strip the nulled out items here
1348 this.startInterval();
1349 } else {
1350 clearInterval(this._interval);
1351 this._interval = null;
1354 this.locked = false;
1356 return true;
1361 * Removes all listeners attached to the given element via addListener.
1362 * Optionally, the node's children can also be purged.
1363 * Optionally, you can specify a specific type of event to remove.
1364 * @method purgeElement
1365 * @param {HTMLElement} el the element to purge
1366 * @param {boolean} recurse recursively purge this element's children
1367 * as well. Use with caution.
1368 * @param {string} sType optional type of listener to purge. If
1369 * left out, all listeners will be removed
1370 * @static
1372 purgeElement: function(el, recurse, sType) {
1373 var elListeners = this.getListeners(el, sType);
1374 if (elListeners) {
1375 for (var i=0,len=elListeners.length; i<len ; ++i) {
1376 var l = elListeners[i];
1377 // can't use the index on the changing collection
1378 //this.removeListener(el, l.type, l.fn, l.index);
1379 this.removeListener(el, l.type, l.fn);
1383 if (recurse && el && el.childNodes) {
1384 for (i=0,len=el.childNodes.length; i<len ; ++i) {
1385 this.purgeElement(el.childNodes[i], recurse, sType);
1391 * Returns all listeners attached to the given element via addListener.
1392 * Optionally, you can specify a specific type of event to return.
1393 * @method getListeners
1394 * @param el {HTMLElement} the element to inspect
1395 * @param sType {string} optional type of listener to return. If
1396 * left out, all listeners will be returned
1397 * @return {Object} the listener. Contains the following fields:
1398 * &nbsp;&nbsp;type: (string) the type of event
1399 * &nbsp;&nbsp;fn: (function) the callback supplied to addListener
1400 * &nbsp;&nbsp;obj: (object) the custom object supplied to addListener
1401 * &nbsp;&nbsp;adjust: (boolean) whether or not to adjust the default scope
1402 * &nbsp;&nbsp;index: (int) its position in the Event util listener cache
1403 * @static
1405 getListeners: function(el, sType) {
1406 var elListeners = [];
1407 if (listeners && listeners.length > 0) {
1408 for (var i=0,len=listeners.length; i<len ; ++i) {
1409 var l = listeners[i];
1410 if ( l && l[this.EL] === el &&
1411 (!sType || sType === l[this.TYPE]) ) {
1412 elListeners.push({
1413 type: l[this.TYPE],
1414 fn: l[this.FN],
1415 obj: l[this.OBJ],
1416 adjust: l[this.ADJ_SCOPE],
1417 index: i
1423 return (elListeners.length) ? elListeners : null;
1427 * Removes all listeners registered by pe.event. Called
1428 * automatically during the unload event.
1429 * @method _unload
1430 * @static
1431 * @private
1433 _unload: function(e) {
1435 var EU = YAHOO.util.Event, i, j, l, len, index;
1437 for (i=0,len=unloadListeners.length; i<len; ++i) {
1438 l = unloadListeners[i];
1439 if (l) {
1440 var scope = window;
1441 if (l[EU.ADJ_SCOPE]) {
1442 if (l[EU.ADJ_SCOPE] === true) {
1443 scope = l[EU.OBJ];
1444 } else {
1445 scope = l[EU.ADJ_SCOPE];
1448 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ] );
1449 unloadListeners[i] = null;
1450 l=null;
1451 scope=null;
1455 unloadListeners = null;
1457 if (listeners && listeners.length > 0) {
1458 j = listeners.length;
1459 while (j) {
1460 index = j-1;
1461 l = listeners[index];
1462 if (l) {
1463 EU.removeListener(l[EU.EL], l[EU.TYPE],
1464 l[EU.FN], index);
1466 j = j - 1;
1468 l=null;
1470 EU.clearCache();
1473 for (i=0,len=legacyEvents.length; i<len; ++i) {
1474 // dereference the element
1475 //delete legacyEvents[i][0];
1476 legacyEvents[i][0] = null;
1478 // delete the array item
1479 //delete legacyEvents[i];
1480 legacyEvents[i] = null;
1483 legacyEvents = null;
1485 EU._simpleRemove(window, "unload", EU._unload);
1490 * Returns scrollLeft
1491 * @method _getScrollLeft
1492 * @static
1493 * @private
1495 _getScrollLeft: function() {
1496 return this._getScroll()[1];
1500 * Returns scrollTop
1501 * @method _getScrollTop
1502 * @static
1503 * @private
1505 _getScrollTop: function() {
1506 return this._getScroll()[0];
1510 * Returns the scrollTop and scrollLeft. Used to calculate the
1511 * pageX and pageY in Internet Explorer
1512 * @method _getScroll
1513 * @static
1514 * @private
1516 _getScroll: function() {
1517 var dd = document.documentElement, db = document.body;
1518 if (dd && (dd.scrollTop || dd.scrollLeft)) {
1519 return [dd.scrollTop, dd.scrollLeft];
1520 } else if (db) {
1521 return [db.scrollTop, db.scrollLeft];
1522 } else {
1523 return [0, 0];
1528 * Adds a DOM event directly without the caching, cleanup, scope adj, etc
1530 * @method _simpleAdd
1531 * @param {HTMLElement} el the element to bind the handler to
1532 * @param {string} sType the type of event handler
1533 * @param {function} fn the callback to invoke
1534 * @param {boolen} capture capture or bubble phase
1535 * @static
1536 * @private
1538 _simpleAdd: function () {
1539 if (window.addEventListener) {
1540 return function(el, sType, fn, capture) {
1541 el.addEventListener(sType, fn, (capture));
1543 } else if (window.attachEvent) {
1544 return function(el, sType, fn, capture) {
1545 el.attachEvent("on" + sType, fn);
1547 } else {
1548 return function(){};
1550 }(),
1553 * Basic remove listener
1555 * @method _simpleRemove
1556 * @param {HTMLElement} el the element to bind the handler to
1557 * @param {string} sType the type of event handler
1558 * @param {function} fn the callback to invoke
1559 * @param {boolen} capture capture or bubble phase
1560 * @static
1561 * @private
1563 _simpleRemove: function() {
1564 if (window.removeEventListener) {
1565 return function (el, sType, fn, capture) {
1566 el.removeEventListener(sType, fn, (capture));
1568 } else if (window.detachEvent) {
1569 return function (el, sType, fn) {
1570 el.detachEvent("on" + sType, fn);
1572 } else {
1573 return function(){};
1578 }();
1580 (function() {
1581 var EU = YAHOO.util.Event;
1584 * YAHOO.util.Event.on is an alias for addListener
1585 * @method on
1586 * @see addListener
1587 * @static
1589 EU.on = EU.addListener;
1591 // YAHOO.mix(EU, YAHOO.util.EventProvider.prototype);
1592 // EU.createEvent("DOMContentReady");
1593 // EU.subscribe("DOMContentReady", EU._load);
1595 if (document && document.body) {
1596 EU._load();
1597 } else {
1598 // EU._simpleAdd(document, "DOMContentLoaded", EU._load);
1599 EU._simpleAdd(window, "load", EU._load);
1601 EU._simpleAdd(window, "unload", EU._unload);
1602 EU._tryPreloadAttach();
1603 })();
1607 * EventProvider is designed to be used with YAHOO.augment to wrap
1608 * CustomEvents in an interface that allows events to be subscribed to
1609 * and fired by name. This makes it possible for implementing code to
1610 * subscribe to an event that either has not been created yet, or will
1611 * not be created at all.
1613 * @Class EventProvider
1615 YAHOO.util.EventProvider = function() { };
1617 YAHOO.util.EventProvider.prototype = {
1620 * Private storage of custom events
1621 * @property __yui_events
1622 * @type Object[]
1623 * @private
1625 __yui_events: null,
1628 * Private storage of custom event subscribers
1629 * @property __yui_subscribers
1630 * @type Object[]
1631 * @private
1633 __yui_subscribers: null,
1636 * Subscribe to a CustomEvent by event type
1638 * @method subscribe
1639 * @param p_type {string} the type, or name of the event
1640 * @param p_fn {function} the function to exectute when the event fires
1641 * @param p_obj
1642 * @param p_obj {Object} An object to be passed along when the event
1643 * fires
1644 * @param p_override {boolean} If true, the obj passed in becomes the
1645 * execution scope of the listener
1647 subscribe: function(p_type, p_fn, p_obj, p_override) {
1649 this.__yui_events = this.__yui_events || {};
1650 var ce = this.__yui_events[p_type];
1652 if (ce) {
1653 ce.subscribe(p_fn, p_obj, p_override);
1654 } else {
1655 this.__yui_subscribers = this.__yui_subscribers || {};
1656 var subs = this.__yui_subscribers;
1657 if (!subs[p_type]) {
1658 subs[p_type] = [];
1660 subs[p_type].push(
1661 { fn: p_fn, obj: p_obj, override: p_override } );
1666 * Unsubscribes the from the specified event
1667 * @method unsubscribe
1668 * @param p_type {string} The type, or name of the event
1669 * @param p_fn {Function} The function to execute
1670 * @param p_obj {Object} The custom object passed to subscribe (optional)
1671 * @return {boolean} true if the subscriber was found and detached.
1673 unsubscribe: function(p_type, p_fn, p_obj) {
1674 this.__yui_events = this.__yui_events || {};
1675 var ce = this.__yui_events[p_type];
1676 if (ce) {
1677 return ce.unsubscribe(p_fn, p_obj);
1678 } else {
1679 return false;
1684 * Creates a new custom event of the specified type. If a custom event
1685 * by that name already exists, it will not be re-created. In either
1686 * case the custom event is returned.
1688 * @method createEvent
1690 * @param p_type {string} the type, or name of the event
1691 * @param p_config {object} optional config params. Valid properties are:
1693 * <ul>
1694 * <li>
1695 * scope: defines the default execution scope. If not defined
1696 * the default scope will be this instance.
1697 * </li>
1698 * <li>
1699 * silent: if true, the custom event will not generate log messages.
1700 * This is false by default.
1701 * </li>
1702 * <li>
1703 * onSubscribeCallback: specifies a callback to execute when the
1704 * event has a new subscriber. This will fire immediately for
1705 * each queued subscriber if any exist prior to the creation of
1706 * the event.
1707 * </li>
1708 * </ul>
1710 * @return {CustomEvent} the custom event
1713 createEvent: function(p_type, p_config) {
1715 this.__yui_events = this.__yui_events || {};
1716 var opts = p_config || {};
1717 var events = this.__yui_events;
1719 if (events[p_type]) {
1720 YAHOO.log("EventProvider: error, event already exists");
1721 } else {
1723 var scope = opts.scope || this;
1724 var silent = opts.silent || null;
1726 var ce = new YAHOO.util.CustomEvent(p_type, scope, silent,
1727 YAHOO.util.CustomEvent.FLAT);
1728 events[p_type] = ce;
1730 if (opts.onSubscribeCallback) {
1731 ce.subscribeEvent.subscribe(opts.onSubscribeCallback);
1734 this.__yui_subscribers = this.__yui_subscribers || {};
1735 var qs = this.__yui_subscribers[p_type];
1737 if (qs) {
1738 for (var i=0; i<qs.length; ++i) {
1739 ce.subscribe(qs[i].fn, qs[i].obj, qs[i].override);
1744 return events[p_type];
1749 * Fire a custom event by name. The callback functions will be executed
1750 * from the scope specified when the event was created, and with the
1751 * following parameters:
1752 * <ul>
1753 * <li>The first argument fire() was executed with</li>
1754 * <li>The custom object (if any) that was passed into the subscribe()
1755 * method</li>
1756 * </ul>
1757 * @method fireEvent
1758 * @param p_type {string} the type, or name of the event
1759 * @param arguments {Object*} an arbitrary set of parameters to pass to
1760 * the handler.
1761 * @return {boolean} the return value from CustomEvent.fire, or null if
1762 * the custom event does not exist.
1764 fireEvent: function(p_type, arg1, arg2, etc) {
1766 this.__yui_events = this.__yui_events || {};
1767 var ce = this.__yui_events[p_type];
1769 if (ce) {
1770 var args = [];
1771 for (var i=1; i<arguments.length; ++i) {
1772 args.push(arguments[i]);
1774 return ce.fire.apply(ce, args);
1775 } else {
1776 YAHOO.log("EventProvider.fire could not find event: " + p_type);
1777 return null;
1782 * Returns true if the custom event of the provided type has been created
1783 * with createEvent.
1784 * @method hasEvent
1785 * @param type {string} the type, or name of the event
1787 hasEvent: function(type) {
1788 if (this.__yui_events) {
1789 if (this.__yui_events[type]) {
1790 return true;
1793 return false;