adding current groupid to grade_export class - soon to be used in plugins
[moodle-pu.git] / lib / yui / event / event-debug.js
blob307ab5245f6b4f578557071541d487b1acac2c31
1 /*
2 Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
5 version: 2.3.0
6 */
8 /**
9 * The CustomEvent class lets you define events for your application
10 * that can be subscribed to by one or more independent component.
12 * @param {String} type The type of event, which is passed to the callback
13 * when the event fires
14 * @param {Object} oScope The context the event will fire from. "this" will
15 * refer to this object in the callback. Default value:
16 * the window object. The listener can override this.
17 * @param {boolean} silent pass true to prevent the event from writing to
18 * the debugsystem
19 * @param {int} signature the signature that the custom event subscriber
20 * will receive. YAHOO.util.CustomEvent.LIST or
21 * YAHOO.util.CustomEvent.FLAT. The default is
22 * YAHOO.util.CustomEvent.LIST.
23 * @namespace YAHOO.util
24 * @class CustomEvent
25 * @constructor
27 YAHOO.util.CustomEvent = function(type, oScope, silent, signature) {
29 /**
30 * The type of event, returned to subscribers when the event fires
31 * @property type
32 * @type string
34 this.type = type;
36 /**
37 * The scope the the event will fire from by default. Defaults to the window
38 * obj
39 * @property scope
40 * @type object
42 this.scope = oScope || window;
44 /**
45 * By default all custom events are logged in the debug build, set silent
46 * to true to disable debug outpu for this event.
47 * @property silent
48 * @type boolean
50 this.silent = silent;
52 /**
53 * Custom events support two styles of arguments provided to the event
54 * subscribers.
55 * <ul>
56 * <li>YAHOO.util.CustomEvent.LIST:
57 * <ul>
58 * <li>param1: event name</li>
59 * <li>param2: array of arguments sent to fire</li>
60 * <li>param3: <optional> a custom object supplied by the subscriber</li>
61 * </ul>
62 * </li>
63 * <li>YAHOO.util.CustomEvent.FLAT
64 * <ul>
65 * <li>param1: the first argument passed to fire. If you need to
66 * pass multiple parameters, use and array or object literal</li>
67 * <li>param2: <optional> a custom object supplied by the subscriber</li>
68 * </ul>
69 * </li>
70 * </ul>
71 * @property signature
72 * @type int
74 this.signature = signature || YAHOO.util.CustomEvent.LIST;
76 /**
77 * The subscribers to this event
78 * @property subscribers
79 * @type Subscriber[]
81 this.subscribers = [];
83 if (!this.silent) {
84 YAHOO.log( "Creating " + this, "info", "Event" );
87 var onsubscribeType = "_YUICEOnSubscribe";
89 // Only add subscribe events for events that are not generated by
90 // CustomEvent
91 if (type !== onsubscribeType) {
93 /**
94 * Custom events provide a custom event that fires whenever there is
95 * a new subscriber to the event. This provides an opportunity to
96 * handle the case where there is a non-repeating event that has
97 * already fired has a new subscriber.
99 * @event subscribeEvent
100 * @type YAHOO.util.CustomEvent
101 * @param {Function} fn The function to execute
102 * @param {Object} obj An object to be passed along when the event
103 * fires
104 * @param {boolean|Object} override If true, the obj passed in becomes
105 * the execution scope of the listener.
106 * if an object, that object becomes the
107 * the execution scope.
109 this.subscribeEvent =
110 new YAHOO.util.CustomEvent(onsubscribeType, this, true);
116 * Subscriber listener sigature constant. The LIST type returns three
117 * parameters: the event type, the array of args passed to fire, and
118 * the optional custom object
119 * @property YAHOO.util.CustomEvent.LIST
120 * @static
121 * @type int
123 YAHOO.util.CustomEvent.LIST = 0;
126 * Subscriber listener sigature constant. The FLAT type returns two
127 * parameters: the first argument passed to fire and the optional
128 * custom object
129 * @property YAHOO.util.CustomEvent.FLAT
130 * @static
131 * @type int
133 YAHOO.util.CustomEvent.FLAT = 1;
135 YAHOO.util.CustomEvent.prototype = {
138 * Subscribes the caller to this event
139 * @method subscribe
140 * @param {Function} fn The function to execute
141 * @param {Object} obj An object to be passed along when the event
142 * fires
143 * @param {boolean|Object} override If true, the obj passed in becomes
144 * the execution scope of the listener.
145 * if an object, that object becomes the
146 * the execution scope.
148 subscribe: function(fn, obj, override) {
150 if (!fn) {
151 throw new Error("Invalid callback for subscriber to '" + this.type + "'");
154 if (this.subscribeEvent) {
155 this.subscribeEvent.fire(fn, obj, override);
158 this.subscribers.push( new YAHOO.util.Subscriber(fn, obj, override) );
162 * Unsubscribes subscribers.
163 * @method unsubscribe
164 * @param {Function} fn The subscribed function to remove, if not supplied
165 * all will be removed
166 * @param {Object} obj The custom object passed to subscribe. This is
167 * optional, but if supplied will be used to
168 * disambiguate multiple listeners that are the same
169 * (e.g., you subscribe many object using a function
170 * that lives on the prototype)
171 * @return {boolean} True if the subscriber was found and detached.
173 unsubscribe: function(fn, obj) {
175 if (!fn) {
176 return this.unsubscribeAll();
179 var found = false;
180 for (var i=0, len=this.subscribers.length; i<len; ++i) {
181 var s = this.subscribers[i];
182 if (s && s.contains(fn, obj)) {
183 this._delete(i);
184 found = true;
188 return found;
192 * Notifies the subscribers. The callback functions will be executed
193 * from the scope specified when the event was created, and with the
194 * following parameters:
195 * <ul>
196 * <li>The type of event</li>
197 * <li>All of the arguments fire() was executed with as an array</li>
198 * <li>The custom object (if any) that was passed into the subscribe()
199 * method</li>
200 * </ul>
201 * @method fire
202 * @param {Object*} arguments an arbitrary set of parameters to pass to
203 * the handler.
204 * @return {boolean} false if one of the subscribers returned false,
205 * true otherwise
207 fire: function() {
208 var len=this.subscribers.length;
209 if (!len && this.silent) {
210 return true;
213 var args=[], ret=true, i, rebuild=false;
215 for (i=0; i<arguments.length; ++i) {
216 args.push(arguments[i]);
219 var argslength = args.length;
221 if (!this.silent) {
222 YAHOO.log( "Firing " + this + ", " +
223 "args: " + args + ", " +
224 "subscribers: " + len,
225 "info", "Event" );
228 for (i=0; i<len; ++i) {
229 var s = this.subscribers[i];
230 if (!s) {
231 rebuild=true;
232 } else {
233 if (!this.silent) {
234 YAHOO.log( this.type + "->" + (i+1) + ": " + s,
235 "info", "Event" );
238 var scope = s.getScope(this.scope);
240 if (this.signature == YAHOO.util.CustomEvent.FLAT) {
241 var param = null;
242 if (args.length > 0) {
243 param = args[0];
245 ret = s.fn.call(scope, param, s.obj);
246 } else {
247 ret = s.fn.call(scope, this.type, args, s.obj);
249 if (false === ret) {
250 if (!this.silent) {
251 YAHOO.log("Event cancelled, subscriber " + i +
252 " of " + len, "info", "Event");
255 //break;
256 return false;
261 if (rebuild) {
262 var newlist=[],subs=this.subscribers;
263 for (i=0,len=subs.length; i<len; ++i) {
264 s = subs[i];
265 newlist.push(subs[i]);
268 this.subscribers=newlist;
271 return true;
275 * Removes all listeners
276 * @method unsubscribeAll
277 * @return {int} The number of listeners unsubscribed
279 unsubscribeAll: function() {
280 for (var i=0, len=this.subscribers.length; i<len; ++i) {
281 this._delete(len - 1 - i);
284 this.subscribers=[];
286 return i;
290 * @method _delete
291 * @private
293 _delete: function(index) {
294 var s = this.subscribers[index];
295 if (s) {
296 delete s.fn;
297 delete s.obj;
300 this.subscribers[index]=null;
304 * @method toString
306 toString: function() {
307 return "CustomEvent: " + "'" + this.type + "', " +
308 "scope: " + this.scope;
313 /////////////////////////////////////////////////////////////////////
316 * Stores the subscriber information to be used when the event fires.
317 * @param {Function} fn The function to execute
318 * @param {Object} obj An object to be passed along when the event fires
319 * @param {boolean} override If true, the obj passed in becomes the execution
320 * scope of the listener
321 * @class Subscriber
322 * @constructor
324 YAHOO.util.Subscriber = function(fn, obj, override) {
327 * The callback that will be execute when the event fires
328 * @property fn
329 * @type function
331 this.fn = fn;
334 * An optional custom object that will passed to the callback when
335 * the event fires
336 * @property obj
337 * @type object
339 this.obj = YAHOO.lang.isUndefined(obj) ? null : obj;
342 * The default execution scope for the event listener is defined when the
343 * event is created (usually the object which contains the event).
344 * By setting override to true, the execution scope becomes the custom
345 * object passed in by the subscriber. If override is an object, that
346 * object becomes the scope.
347 * @property override
348 * @type boolean|object
350 this.override = override;
355 * Returns the execution scope for this listener. If override was set to true
356 * the custom obj will be the scope. If override is an object, that is the
357 * scope, otherwise the default scope will be used.
358 * @method getScope
359 * @param {Object} defaultScope the scope to use if this listener does not
360 * override it.
362 YAHOO.util.Subscriber.prototype.getScope = function(defaultScope) {
363 if (this.override) {
364 if (this.override === true) {
365 return this.obj;
366 } else {
367 return this.override;
370 return defaultScope;
374 * Returns true if the fn and obj match this objects properties.
375 * Used by the unsubscribe method to match the right subscriber.
377 * @method contains
378 * @param {Function} fn the function to execute
379 * @param {Object} obj an object to be passed along when the event fires
380 * @return {boolean} true if the supplied arguments match this
381 * subscriber's signature.
383 YAHOO.util.Subscriber.prototype.contains = function(fn, obj) {
384 if (obj) {
385 return (this.fn == fn && this.obj == obj);
386 } else {
387 return (this.fn == fn);
392 * @method toString
394 YAHOO.util.Subscriber.prototype.toString = function() {
395 return "Subscriber { obj: " + this.obj +
396 ", override: " + (this.override || "no") + " }";
400 * The Event Utility provides utilities for managing DOM Events and tools
401 * for building event systems
403 * @module event
404 * @title Event Utility
405 * @namespace YAHOO.util
406 * @requires yahoo
409 // The first instance of Event will win if it is loaded more than once.
410 // @TODO this needs to be changed so that only the state data that needs to
411 // be preserved is kept, while methods are overwritten/added as needed.
412 // This means that the module pattern can't be used.
413 if (!YAHOO.util.Event) {
416 * The event utility provides functions to add and remove event listeners,
417 * event cleansing. It also tries to automatically remove listeners it
418 * registers during the unload event.
420 * @class Event
421 * @static
423 YAHOO.util.Event = function() {
426 * True after the onload event has fired
427 * @property loadComplete
428 * @type boolean
429 * @static
430 * @private
432 var loadComplete = false;
435 * True when the document is initially usable
436 * @property DOMReady
437 * @type boolean
438 * @static
439 * @private
441 var DOMReady = false;
444 * Cache of wrapped listeners
445 * @property listeners
446 * @type array
447 * @static
448 * @private
450 var listeners = [];
453 * User-defined unload function that will be fired before all events
454 * are detached
455 * @property unloadListeners
456 * @type array
457 * @static
458 * @private
460 var unloadListeners = [];
463 * Cache of DOM0 event handlers to work around issues with DOM2 events
464 * in Safari
465 * @property legacyEvents
466 * @static
467 * @private
469 var legacyEvents = [];
472 * Listener stack for DOM0 events
473 * @property legacyHandlers
474 * @static
475 * @private
477 var legacyHandlers = [];
480 * The number of times to poll after window.onload. This number is
481 * increased if additional late-bound handlers are requested after
482 * the page load.
483 * @property retryCount
484 * @static
485 * @private
487 var retryCount = 0;
490 * onAvailable listeners
491 * @property onAvailStack
492 * @static
493 * @private
495 var onAvailStack = [];
498 * Lookup table for legacy events
499 * @property legacyMap
500 * @static
501 * @private
503 var legacyMap = [];
506 * Counter for auto id generation
507 * @property counter
508 * @static
509 * @private
511 var counter = 0;
514 * Normalized keycodes for webkit/safari
515 * @property webkitKeymap
516 * @type {int: int}
517 * @private
518 * @static
519 * @final
521 var webkitKeymap = {
522 63232: 38, // up
523 63233: 40, // down
524 63234: 37, // left
525 63235: 39 // right
528 return {
531 * The number of times we should look for elements that are not
532 * in the DOM at the time the event is requested after the document
533 * has been loaded. The default is 4000@amp;10 ms, so it will poll
534 * for 40 seconds or until all outstanding handlers are bound
535 * (whichever comes first).
536 * @property POLL_RETRYS
537 * @type int
538 * @static
539 * @final
541 POLL_RETRYS: 4000,
544 * The poll interval in milliseconds
545 * @property POLL_INTERVAL
546 * @type int
547 * @static
548 * @final
550 POLL_INTERVAL: 10,
553 * Element to bind, int constant
554 * @property EL
555 * @type int
556 * @static
557 * @final
559 EL: 0,
562 * Type of event, int constant
563 * @property TYPE
564 * @type int
565 * @static
566 * @final
568 TYPE: 1,
571 * Function to execute, int constant
572 * @property FN
573 * @type int
574 * @static
575 * @final
577 FN: 2,
580 * Function wrapped for scope correction and cleanup, int constant
581 * @property WFN
582 * @type int
583 * @static
584 * @final
586 WFN: 3,
589 * Object passed in by the user that will be returned as a
590 * parameter to the callback, int constant
591 * @property OBJ
592 * @type int
593 * @static
594 * @final
596 OBJ: 3,
599 * Adjusted scope, either the element we are registering the event
600 * on or the custom object passed in by the listener, int constant
601 * @property ADJ_SCOPE
602 * @type int
603 * @static
604 * @final
606 ADJ_SCOPE: 4,
609 * addListener/removeListener can throw errors in unexpected scenarios.
610 * These errors are suppressed, the method returns false, and this property
611 * is set
612 * @property lastError
613 * @static
614 * @type Error
616 lastError: null,
619 * Safari detection
620 * @property isSafari
621 * @private
622 * @static
623 * @deprecated use YAHOO.env.ua.webkit
625 isSafari: YAHOO.env.ua.webkit,
628 * webkit version
629 * @property webkit
630 * @type string
631 * @private
632 * @static
633 * @deprecated use YAHOO.env.ua.webkit
635 webkit: YAHOO.env.ua.webkit,
638 * IE detection
639 * @property isIE
640 * @private
641 * @static
642 * @deprecated use YAHOO.env.ua.ie
644 isIE: YAHOO.env.ua.ie,
647 * poll handle
648 * @property _interval
649 * @static
650 * @private
652 _interval: null,
655 * @method startInterval
656 * @static
657 * @private
659 startInterval: function() {
660 if (!this._interval) {
661 var self = this;
662 var callback = function() { self._tryPreloadAttach(); };
663 this._interval = setInterval(callback, this.POLL_INTERVAL);
668 * Executes the supplied callback when the item with the supplied
669 * id is found. This is meant to be used to execute behavior as
670 * soon as possible as the page loads. If you use this after the
671 * initial page load it will poll for a fixed time for the element.
672 * The number of times it will poll and the frequency are
673 * configurable. By default it will poll for 10 seconds.
675 * <p>The callback is executed with a single parameter:
676 * the custom object parameter, if provided.</p>
678 * @method onAvailable
680 * @param {string} p_id the id of the element to look for.
681 * @param {function} p_fn what to execute when the element is found.
682 * @param {object} p_obj an optional object to be passed back as
683 * a parameter to p_fn.
684 * @param {boolean|object} p_override If set to true, p_fn will execute
685 * in the scope of p_obj, if set to an object it
686 * will execute in the scope of that object
688 * @static
690 onAvailable: function(p_id, p_fn, p_obj, p_override) {
691 onAvailStack.push( { id: p_id,
692 fn: p_fn,
693 obj: p_obj,
694 override: p_override,
695 checkReady: false } );
696 retryCount = this.POLL_RETRYS;
697 this.startInterval();
701 * Executes the supplied callback when the DOM is first usable. This
702 * will execute immediately if called after the DOMReady event has
703 * fired. @todo the DOMContentReady event does not fire when the
704 * script is dynamically injected into the page. This means the
705 * DOMReady custom event will never fire in FireFox or Opera when the
706 * library is injected. It _will_ fire in Safari, and the IE
707 * implementation would allow for us to fire it if the defered script
708 * is not available. We want this to behave the same in all browsers.
709 * Is there a way to identify when the script has been injected
710 * instead of included inline? Is there a way to know whether the
711 * window onload event has fired without having had a listener attached
712 * to it when it did so?
714 * <p>The callback is a CustomEvent, so the signature is:</p>
715 * <p>type <string>, args <array>, customobject <object></p>
716 * <p>For DOMReady events, there are no fire argments, so the
717 * signature is:</p>
718 * <p>"DOMReady", [], obj</p>
721 * @method onDOMReady
723 * @param {function} p_fn what to execute when the element is found.
724 * @param {object} p_obj an optional object to be passed back as
725 * a parameter to p_fn.
726 * @param {boolean|object} p_scope If set to true, p_fn will execute
727 * in the scope of p_obj, if set to an object it
728 * will execute in the scope of that object
730 * @static
732 onDOMReady: function(p_fn, p_obj, p_override) {
733 if (DOMReady) {
734 setTimeout(function() {
735 var s = window;
736 if (p_override) {
737 if (p_override === true) {
738 s = p_obj;
739 } else {
740 s = p_override;
743 p_fn.call(s, "DOMReady", [], p_obj);
744 }, 0);
745 } else {
746 this.DOMReadyEvent.subscribe(p_fn, p_obj, p_override);
751 * Works the same way as onAvailable, but additionally checks the
752 * state of sibling elements to determine if the content of the
753 * available element is safe to modify.
755 * <p>The callback is executed with a single parameter:
756 * the custom object parameter, if provided.</p>
758 * @method onContentReady
760 * @param {string} p_id the id of the element to look for.
761 * @param {function} p_fn what to execute when the element is ready.
762 * @param {object} p_obj an optional object to be passed back as
763 * a parameter to p_fn.
764 * @param {boolean|object} p_override If set to true, p_fn will execute
765 * in the scope of p_obj. If an object, p_fn will
766 * exectute in the scope of that object
768 * @static
770 onContentReady: function(p_id, p_fn, p_obj, p_override) {
771 onAvailStack.push( { id: p_id,
772 fn: p_fn,
773 obj: p_obj,
774 override: p_override,
775 checkReady: true } );
777 retryCount = this.POLL_RETRYS;
778 this.startInterval();
782 * Appends an event handler
784 * @method addListener
786 * @param {String|HTMLElement|Array|NodeList} el An id, an element
787 * reference, or a collection of ids and/or elements to assign the
788 * listener to.
789 * @param {String} sType The type of event to append
790 * @param {Function} fn The method the event invokes
791 * @param {Object} obj An arbitrary object that will be
792 * passed as a parameter to the handler
793 * @param {Boolean|object} override If true, the obj passed in becomes
794 * the execution scope of the listener. If an
795 * object, this object becomes the execution
796 * scope.
797 * @return {Boolean} True if the action was successful or defered,
798 * false if one or more of the elements
799 * could not have the listener attached,
800 * or if the operation throws an exception.
801 * @static
803 addListener: function(el, sType, fn, obj, override) {
805 if (!fn || !fn.call) {
806 // throw new TypeError(sType + " addListener call failed, callback undefined");
807 YAHOO.log(sType + " addListener call failed, invalid callback", "error", "Event");
808 return false;
811 // The el argument can be an array of elements or element ids.
812 if ( this._isValidCollection(el)) {
813 var ok = true;
814 for (var i=0,len=el.length; i<len; ++i) {
815 ok = this.on(el[i],
816 sType,
817 fn,
818 obj,
819 override) && ok;
821 return ok;
823 } else if (YAHOO.lang.isString(el)) {
824 var oEl = this.getEl(el);
825 // If the el argument is a string, we assume it is
826 // actually the id of the element. If the page is loaded
827 // we convert el to the actual element, otherwise we
828 // defer attaching the event until onload event fires
830 // check to see if we need to delay hooking up the event
831 // until after the page loads.
832 if (oEl) {
833 el = oEl;
834 } else {
835 // defer adding the event until the element is available
836 this.onAvailable(el, function() {
837 YAHOO.util.Event.on(el, sType, fn, obj, override);
840 return true;
844 // Element should be an html element or an array if we get
845 // here.
846 if (!el) {
847 // this.logger.debug("unable to attach event " + sType);
848 return false;
851 // we need to make sure we fire registered unload events
852 // prior to automatically unhooking them. So we hang on to
853 // these instead of attaching them to the window and fire the
854 // handles explicitly during our one unload event.
855 if ("unload" == sType && obj !== this) {
856 unloadListeners[unloadListeners.length] =
857 [el, sType, fn, obj, override];
858 return true;
861 // this.logger.debug("Adding handler: " + el + ", " + sType);
863 // if the user chooses to override the scope, we use the custom
864 // object passed in, otherwise the executing scope will be the
865 // HTML element that the event is registered on
866 var scope = el;
867 if (override) {
868 if (override === true) {
869 scope = obj;
870 } else {
871 scope = override;
875 // wrap the function so we can return the obj object when
876 // the event fires;
877 var wrappedFn = function(e) {
878 return fn.call(scope, YAHOO.util.Event.getEvent(e),
879 obj);
882 var li = [el, sType, fn, wrappedFn, scope];
883 var index = listeners.length;
884 // cache the listener so we can try to automatically unload
885 listeners[index] = li;
887 if (this.useLegacyEvent(el, sType)) {
888 var legacyIndex = this.getLegacyIndex(el, sType);
890 // Add a new dom0 wrapper if one is not detected for this
891 // element
892 if ( legacyIndex == -1 ||
893 el != legacyEvents[legacyIndex][0] ) {
895 legacyIndex = legacyEvents.length;
896 legacyMap[el.id + sType] = legacyIndex;
898 // cache the signature for the DOM0 event, and
899 // include the existing handler for the event, if any
900 legacyEvents[legacyIndex] =
901 [el, sType, el["on" + sType]];
902 legacyHandlers[legacyIndex] = [];
904 el["on" + sType] =
905 function(e) {
906 YAHOO.util.Event.fireLegacyEvent(
907 YAHOO.util.Event.getEvent(e), legacyIndex);
911 // add a reference to the wrapped listener to our custom
912 // stack of events
913 //legacyHandlers[legacyIndex].push(index);
914 legacyHandlers[legacyIndex].push(li);
916 } else {
917 try {
918 this._simpleAdd(el, sType, wrappedFn, false);
919 } catch(ex) {
920 // handle an error trying to attach an event. If it fails
921 // we need to clean up the cache
922 this.lastError = ex;
923 this.removeListener(el, sType, fn);
924 return false;
928 return true;
933 * When using legacy events, the handler is routed to this object
934 * so we can fire our custom listener stack.
935 * @method fireLegacyEvent
936 * @static
937 * @private
939 fireLegacyEvent: function(e, legacyIndex) {
940 // this.logger.debug("fireLegacyEvent " + legacyIndex);
941 var ok=true,le,lh,li,scope,ret;
943 lh = legacyHandlers[legacyIndex];
944 for (var i=0,len=lh.length; i<len; ++i) {
945 li = lh[i];
946 if ( li && li[this.WFN] ) {
947 scope = li[this.ADJ_SCOPE];
948 ret = li[this.WFN].call(scope, e);
949 ok = (ok && ret);
953 // Fire the original handler if we replaced one. We fire this
954 // after the other events to keep stopPropagation/preventDefault
955 // that happened in the DOM0 handler from touching our DOM2
956 // substitute
957 le = legacyEvents[legacyIndex];
958 if (le && le[2]) {
959 le[2](e);
962 return ok;
966 * Returns the legacy event index that matches the supplied
967 * signature
968 * @method getLegacyIndex
969 * @static
970 * @private
972 getLegacyIndex: function(el, sType) {
973 var key = this.generateId(el) + sType;
974 if (typeof legacyMap[key] == "undefined") {
975 return -1;
976 } else {
977 return legacyMap[key];
982 * Logic that determines when we should automatically use legacy
983 * events instead of DOM2 events. Currently this is limited to old
984 * Safari browsers with a broken preventDefault
985 * @method useLegacyEvent
986 * @static
987 * @private
989 useLegacyEvent: function(el, sType) {
990 if (this.webkit && ("click"==sType || "dblclick"==sType)) {
991 var v = parseInt(this.webkit, 10);
992 if (!isNaN(v) && v<418) {
993 return true;
996 return false;
1000 * Removes an event listener
1002 * @method removeListener
1004 * @param {String|HTMLElement|Array|NodeList} el An id, an element
1005 * reference, or a collection of ids and/or elements to remove
1006 * the listener from.
1007 * @param {String} sType the type of event to remove.
1008 * @param {Function} fn the method the event invokes. If fn is
1009 * undefined, then all event handlers for the type of event are
1010 * removed.
1011 * @return {boolean} true if the unbind was successful, false
1012 * otherwise.
1013 * @static
1015 removeListener: function(el, sType, fn) {
1016 var i, len;
1018 // The el argument can be a string
1019 if (typeof el == "string") {
1020 el = this.getEl(el);
1021 // The el argument can be an array of elements or element ids.
1022 } else if ( this._isValidCollection(el)) {
1023 var ok = true;
1024 for (i=0,len=el.length; i<len; ++i) {
1025 ok = ( this.removeListener(el[i], sType, fn) && ok );
1027 return ok;
1030 if (!fn || !fn.call) {
1031 // this.logger.debug("Error, function is not valid " + fn);
1032 //return false;
1033 return this.purgeElement(el, false, sType);
1036 if ("unload" == sType) {
1038 for (i=0, len=unloadListeners.length; i<len; i++) {
1039 var li = unloadListeners[i];
1040 if (li &&
1041 li[0] == el &&
1042 li[1] == sType &&
1043 li[2] == fn) {
1044 //unloadListeners.splice(i, 1);
1045 unloadListeners[i]=null;
1046 return true;
1050 return false;
1053 var cacheItem = null;
1055 // The index is a hidden parameter; needed to remove it from
1056 // the method signature because it was tempting users to
1057 // try and take advantage of it, which is not possible.
1058 var index = arguments[3];
1060 if ("undefined" == typeof index) {
1061 index = this._getCacheIndex(el, sType, fn);
1064 if (index >= 0) {
1065 cacheItem = listeners[index];
1068 if (!el || !cacheItem) {
1069 // this.logger.debug("cached listener not found");
1070 return false;
1073 // this.logger.debug("Removing handler: " + el + ", " + sType);
1075 if (this.useLegacyEvent(el, sType)) {
1076 var legacyIndex = this.getLegacyIndex(el, sType);
1077 var llist = legacyHandlers[legacyIndex];
1078 if (llist) {
1079 for (i=0, len=llist.length; i<len; ++i) {
1080 li = llist[i];
1081 if (li &&
1082 li[this.EL] == el &&
1083 li[this.TYPE] == sType &&
1084 li[this.FN] == fn) {
1085 //llist.splice(i, 1);
1086 llist[i]=null;
1087 break;
1092 } else {
1093 try {
1094 this._simpleRemove(el, sType, cacheItem[this.WFN], false);
1095 } catch(ex) {
1096 this.lastError = ex;
1097 return false;
1101 // removed the wrapped handler
1102 delete listeners[index][this.WFN];
1103 delete listeners[index][this.FN];
1104 //listeners.splice(index, 1);
1105 listeners[index]=null;
1107 return true;
1112 * Returns the event's target element. Safari sometimes provides
1113 * a text node, and this is automatically resolved to the text
1114 * node's parent so that it behaves like other browsers.
1115 * @method getTarget
1116 * @param {Event} ev the event
1117 * @param {boolean} resolveTextNode when set to true the target's
1118 * parent will be returned if the target is a
1119 * text node. @deprecated, the text node is
1120 * now resolved automatically
1121 * @return {HTMLElement} the event's target
1122 * @static
1124 getTarget: function(ev, resolveTextNode) {
1125 var t = ev.target || ev.srcElement;
1126 return this.resolveTextNode(t);
1130 * In some cases, some browsers will return a text node inside
1131 * the actual element that was targeted. This normalizes the
1132 * return value for getTarget and getRelatedTarget.
1133 * @method resolveTextNode
1134 * @param {HTMLElement} node node to resolve
1135 * @return {HTMLElement} the normized node
1136 * @static
1138 resolveTextNode: function(node) {
1139 if (node && 3 == node.nodeType) {
1140 return node.parentNode;
1141 } else {
1142 return node;
1147 * Returns the event's pageX
1148 * @method getPageX
1149 * @param {Event} ev the event
1150 * @return {int} the event's pageX
1151 * @static
1153 getPageX: function(ev) {
1154 var x = ev.pageX;
1155 if (!x && 0 !== x) {
1156 x = ev.clientX || 0;
1158 if ( this.isIE ) {
1159 x += this._getScrollLeft();
1163 return x;
1167 * Returns the event's pageY
1168 * @method getPageY
1169 * @param {Event} ev the event
1170 * @return {int} the event's pageY
1171 * @static
1173 getPageY: function(ev) {
1174 var y = ev.pageY;
1175 if (!y && 0 !== y) {
1176 y = ev.clientY || 0;
1178 if ( this.isIE ) {
1179 y += this._getScrollTop();
1184 return y;
1188 * Returns the pageX and pageY properties as an indexed array.
1189 * @method getXY
1190 * @param {Event} ev the event
1191 * @return {[x, y]} the pageX and pageY properties of the event
1192 * @static
1194 getXY: function(ev) {
1195 return [this.getPageX(ev), this.getPageY(ev)];
1199 * Returns the event's related target
1200 * @method getRelatedTarget
1201 * @param {Event} ev the event
1202 * @return {HTMLElement} the event's relatedTarget
1203 * @static
1205 getRelatedTarget: function(ev) {
1206 var t = ev.relatedTarget;
1207 if (!t) {
1208 if (ev.type == "mouseout") {
1209 t = ev.toElement;
1210 } else if (ev.type == "mouseover") {
1211 t = ev.fromElement;
1215 return this.resolveTextNode(t);
1219 * Returns the time of the event. If the time is not included, the
1220 * event is modified using the current time.
1221 * @method getTime
1222 * @param {Event} ev the event
1223 * @return {Date} the time of the event
1224 * @static
1226 getTime: function(ev) {
1227 if (!ev.time) {
1228 var t = new Date().getTime();
1229 try {
1230 ev.time = t;
1231 } catch(ex) {
1232 this.lastError = ex;
1233 return t;
1237 return ev.time;
1241 * Convenience method for stopPropagation + preventDefault
1242 * @method stopEvent
1243 * @param {Event} ev the event
1244 * @static
1246 stopEvent: function(ev) {
1247 this.stopPropagation(ev);
1248 this.preventDefault(ev);
1252 * Stops event propagation
1253 * @method stopPropagation
1254 * @param {Event} ev the event
1255 * @static
1257 stopPropagation: function(ev) {
1258 if (ev.stopPropagation) {
1259 ev.stopPropagation();
1260 } else {
1261 ev.cancelBubble = true;
1266 * Prevents the default behavior of the event
1267 * @method preventDefault
1268 * @param {Event} ev the event
1269 * @static
1271 preventDefault: function(ev) {
1272 if (ev.preventDefault) {
1273 ev.preventDefault();
1274 } else {
1275 ev.returnValue = false;
1280 * Finds the event in the window object, the caller's arguments, or
1281 * in the arguments of another method in the callstack. This is
1282 * executed automatically for events registered through the event
1283 * manager, so the implementer should not normally need to execute
1284 * this function at all.
1285 * @method getEvent
1286 * @param {Event} e the event parameter from the handler
1287 * @return {Event} the event
1288 * @static
1290 getEvent: function(e) {
1291 var ev = e || window.event;
1293 if (!ev) {
1294 var c = this.getEvent.caller;
1295 while (c) {
1296 ev = c.arguments[0];
1297 if (ev && Event == ev.constructor) {
1298 break;
1300 c = c.caller;
1304 return ev;
1308 * Returns the charcode for an event
1309 * @method getCharCode
1310 * @param {Event} ev the event
1311 * @return {int} the event's charCode
1312 * @static
1314 getCharCode: function(ev) {
1315 var code = ev.keyCode || ev.charCode || 0;
1317 // webkit normalization
1318 if (YAHOO.env.ua.webkit && (code in webkitKeymap)) {
1319 code = webkitKeymap[code];
1321 return code;
1325 * Locating the saved event handler data by function ref
1327 * @method _getCacheIndex
1328 * @static
1329 * @private
1331 _getCacheIndex: function(el, sType, fn) {
1332 for (var i=0,len=listeners.length; i<len; ++i) {
1333 var li = listeners[i];
1334 if ( li &&
1335 li[this.FN] == fn &&
1336 li[this.EL] == el &&
1337 li[this.TYPE] == sType ) {
1338 return i;
1342 return -1;
1346 * Generates an unique ID for the element if it does not already
1347 * have one.
1348 * @method generateId
1349 * @param el the element to create the id for
1350 * @return {string} the resulting id of the element
1351 * @static
1353 generateId: function(el) {
1354 var id = el.id;
1356 if (!id) {
1357 id = "yuievtautoid-" + counter;
1358 ++counter;
1359 el.id = id;
1362 return id;
1367 * We want to be able to use getElementsByTagName as a collection
1368 * to attach a group of events to. Unfortunately, different
1369 * browsers return different types of collections. This function
1370 * tests to determine if the object is array-like. It will also
1371 * fail if the object is an array, but is empty.
1372 * @method _isValidCollection
1373 * @param o the object to test
1374 * @return {boolean} true if the object is array-like and populated
1375 * @static
1376 * @private
1378 _isValidCollection: function(o) {
1379 try {
1380 return ( o && // o is something
1381 o.length && // o is indexed
1382 typeof o != "string" && // o is not a string
1383 !o.tagName && // o is not an HTML element
1384 !o.alert && // o is not a window
1385 typeof o[0] != "undefined" );
1386 } catch(e) {
1387 YAHOO.log("_isValidCollection threw an error, assuming that " +
1388 " this is a cross frame problem and not a collection", warn);
1389 return false;
1395 * @private
1396 * @property elCache
1397 * DOM element cache
1398 * @static
1399 * @deprecated Elements are not cached due to issues that arise when
1400 * elements are removed and re-added
1402 elCache: {},
1405 * We cache elements bound by id because when the unload event
1406 * fires, we can no longer use document.getElementById
1407 * @method getEl
1408 * @static
1409 * @private
1410 * @deprecated Elements are not cached any longer
1412 getEl: function(id) {
1413 return document.getElementById(id);
1417 * Clears the element cache
1418 * @deprecated Elements are not cached any longer
1419 * @method clearCache
1420 * @static
1421 * @private
1423 clearCache: function() { },
1426 * Custom event the fires when the dom is initially usable
1427 * @event DOMReadyEvent
1429 DOMReadyEvent: new YAHOO.util.CustomEvent("DOMReady", this),
1432 * hook up any deferred listeners
1433 * @method _load
1434 * @static
1435 * @private
1437 _load: function(e) {
1439 if (!loadComplete) {
1440 loadComplete = true;
1441 var EU = YAHOO.util.Event;
1443 // Just in case DOMReady did not go off for some reason
1444 EU._ready();
1446 // Available elements may not have been detected before the
1447 // window load event fires. Try to find them now so that the
1448 // the user is more likely to get the onAvailable notifications
1449 // before the window load notification
1450 EU._tryPreloadAttach();
1452 // Remove the listener to assist with the IE memory issue, but not
1453 // for other browsers because FF 1.0x does not like it.
1454 //if (this.isIE) {
1455 //EU._simpleRemove(window, "load", EU._load);
1461 * Fires the DOMReady event listeners the first time the document is
1462 * usable.
1463 * @method _ready
1464 * @static
1465 * @private
1467 _ready: function(e) {
1468 if (!DOMReady) {
1469 DOMReady=true;
1470 var EU = YAHOO.util.Event;
1472 // Fire the content ready custom event
1473 EU.DOMReadyEvent.fire();
1475 // Remove the DOMContentLoaded (FF/Opera)
1476 EU._simpleRemove(document, "DOMContentLoaded", EU._ready);
1481 * Polling function that runs before the onload event fires,
1482 * attempting to attach to DOM Nodes as soon as they are
1483 * available
1484 * @method _tryPreloadAttach
1485 * @static
1486 * @private
1488 _tryPreloadAttach: function() {
1490 if (this.locked) {
1491 return false;
1494 if (this.isIE) {
1495 // Hold off if DOMReady has not fired and check current
1496 // readyState to protect against the IE operation aborted
1497 // issue.
1498 //if (!DOMReady || "complete" !== document.readyState) {
1499 if (!DOMReady) {
1500 this.startInterval();
1501 return false;
1505 this.locked = true;
1507 // this.logger.debug("tryPreloadAttach");
1509 // keep trying until after the page is loaded. We need to
1510 // check the page load state prior to trying to bind the
1511 // elements so that we can be certain all elements have been
1512 // tested appropriately
1513 var tryAgain = !loadComplete;
1514 if (!tryAgain) {
1515 tryAgain = (retryCount > 0);
1518 // onAvailable
1519 var notAvail = [];
1521 var executeItem = function (el, item) {
1522 var scope = el;
1523 if (item.override) {
1524 if (item.override === true) {
1525 scope = item.obj;
1526 } else {
1527 scope = item.override;
1530 item.fn.call(scope, item.obj);
1533 var i,len,item,el;
1535 // onAvailable
1536 for (i=0,len=onAvailStack.length; i<len; ++i) {
1537 item = onAvailStack[i];
1538 if (item && !item.checkReady) {
1539 el = this.getEl(item.id);
1540 if (el) {
1541 executeItem(el, item);
1542 onAvailStack[i] = null;
1543 } else {
1544 notAvail.push(item);
1549 // onContentReady
1550 for (i=0,len=onAvailStack.length; i<len; ++i) {
1551 item = onAvailStack[i];
1552 if (item && item.checkReady) {
1553 el = this.getEl(item.id);
1555 if (el) {
1556 // The element is available, but not necessarily ready
1557 // @todo should we test parentNode.nextSibling?
1558 if (loadComplete || el.nextSibling) {
1559 executeItem(el, item);
1560 onAvailStack[i] = null;
1562 } else {
1563 notAvail.push(item);
1568 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
1570 if (tryAgain) {
1571 // we may need to strip the nulled out items here
1572 this.startInterval();
1573 } else {
1574 clearInterval(this._interval);
1575 this._interval = null;
1578 this.locked = false;
1580 return true;
1585 * Removes all listeners attached to the given element via addListener.
1586 * Optionally, the node's children can also be purged.
1587 * Optionally, you can specify a specific type of event to remove.
1588 * @method purgeElement
1589 * @param {HTMLElement} el the element to purge
1590 * @param {boolean} recurse recursively purge this element's children
1591 * as well. Use with caution.
1592 * @param {string} sType optional type of listener to purge. If
1593 * left out, all listeners will be removed
1594 * @static
1596 purgeElement: function(el, recurse, sType) {
1597 var elListeners = this.getListeners(el, sType);
1598 if (elListeners) {
1599 for (var i=0,len=elListeners.length; i<len ; ++i) {
1600 var l = elListeners[i];
1601 // can't use the index on the changing collection
1602 this.removeListener(el, l.type, l.fn, l.index);
1603 //this.removeListener(el, l.type, l.fn);
1607 if (recurse && el && el.childNodes) {
1608 for (i=0,len=el.childNodes.length; i<len ; ++i) {
1609 this.purgeElement(el.childNodes[i], recurse, sType);
1615 * Returns all listeners attached to the given element via addListener.
1616 * Optionally, you can specify a specific type of event to return.
1617 * @method getListeners
1618 * @param el {HTMLElement} the element to inspect
1619 * @param sType {string} optional type of listener to return. If
1620 * left out, all listeners will be returned
1621 * @return {Object} the listener. Contains the following fields:
1622 * &nbsp;&nbsp;type: (string) the type of event
1623 * &nbsp;&nbsp;fn: (function) the callback supplied to addListener
1624 * &nbsp;&nbsp;obj: (object) the custom object supplied to addListener
1625 * &nbsp;&nbsp;adjust: (boolean) whether or not to adjust the default scope
1626 * &nbsp;&nbsp;index: (int) its position in the Event util listener cache
1627 * @static
1629 getListeners: function(el, sType) {
1630 var results=[], searchLists;
1631 if (!sType) {
1632 searchLists = [listeners, unloadListeners];
1633 } else if (sType == "unload") {
1634 searchLists = [unloadListeners];
1635 } else {
1636 searchLists = [listeners];
1639 for (var j=0;j<searchLists.length; ++j) {
1640 var searchList = searchLists[j];
1641 if (searchList && searchList.length > 0) {
1642 for (var i=0,len=searchList.length; i<len ; ++i) {
1643 var l = searchList[i];
1644 if ( l && l[this.EL] === el &&
1645 (!sType || sType === l[this.TYPE]) ) {
1646 results.push({
1647 type: l[this.TYPE],
1648 fn: l[this.FN],
1649 obj: l[this.OBJ],
1650 adjust: l[this.ADJ_SCOPE],
1651 index: i
1658 return (results.length) ? results : null;
1662 * Removes all listeners registered by pe.event. Called
1663 * automatically during the unload event.
1664 * @method _unload
1665 * @static
1666 * @private
1668 _unload: function(e) {
1670 var EU = YAHOO.util.Event, i, j, l, len, index;
1672 for (i=0,len=unloadListeners.length; i<len; ++i) {
1673 l = unloadListeners[i];
1674 if (l) {
1675 var scope = window;
1676 if (l[EU.ADJ_SCOPE]) {
1677 if (l[EU.ADJ_SCOPE] === true) {
1678 scope = l[EU.OBJ];
1679 } else {
1680 scope = l[EU.ADJ_SCOPE];
1683 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ] );
1684 unloadListeners[i] = null;
1685 l=null;
1686 scope=null;
1690 unloadListeners = null;
1692 if (listeners && listeners.length > 0) {
1693 j = listeners.length;
1694 while (j) {
1695 index = j-1;
1696 l = listeners[index];
1697 if (l) {
1698 EU.removeListener(l[EU.EL], l[EU.TYPE], l[EU.FN], index);
1700 j = j - 1;
1702 l=null;
1704 EU.clearCache();
1707 for (i=0,len=legacyEvents.length; i<len; ++i) {
1708 // dereference the element
1709 //delete legacyEvents[i][0];
1710 legacyEvents[i][0] = null;
1712 // delete the array item
1713 //delete legacyEvents[i];
1714 legacyEvents[i] = null;
1717 legacyEvents = null;
1719 EU._simpleRemove(window, "unload", EU._unload);
1724 * Returns scrollLeft
1725 * @method _getScrollLeft
1726 * @static
1727 * @private
1729 _getScrollLeft: function() {
1730 return this._getScroll()[1];
1734 * Returns scrollTop
1735 * @method _getScrollTop
1736 * @static
1737 * @private
1739 _getScrollTop: function() {
1740 return this._getScroll()[0];
1744 * Returns the scrollTop and scrollLeft. Used to calculate the
1745 * pageX and pageY in Internet Explorer
1746 * @method _getScroll
1747 * @static
1748 * @private
1750 _getScroll: function() {
1751 var dd = document.documentElement, db = document.body;
1752 if (dd && (dd.scrollTop || dd.scrollLeft)) {
1753 return [dd.scrollTop, dd.scrollLeft];
1754 } else if (db) {
1755 return [db.scrollTop, db.scrollLeft];
1756 } else {
1757 return [0, 0];
1762 * Used by old versions of CustomEvent, restored for backwards
1763 * compatibility
1764 * @method regCE
1765 * @private
1766 * @static
1767 * @deprecated still here for backwards compatibility
1769 regCE: function() {
1770 // does nothing
1774 * Adds a DOM event directly without the caching, cleanup, scope adj, etc
1776 * @method _simpleAdd
1777 * @param {HTMLElement} el the element to bind the handler to
1778 * @param {string} sType the type of event handler
1779 * @param {function} fn the callback to invoke
1780 * @param {boolen} capture capture or bubble phase
1781 * @static
1782 * @private
1784 _simpleAdd: function () {
1785 if (window.addEventListener) {
1786 return function(el, sType, fn, capture) {
1787 el.addEventListener(sType, fn, (capture));
1789 } else if (window.attachEvent) {
1790 return function(el, sType, fn, capture) {
1791 el.attachEvent("on" + sType, fn);
1793 } else {
1794 return function(){};
1796 }(),
1799 * Basic remove listener
1801 * @method _simpleRemove
1802 * @param {HTMLElement} el the element to bind the handler to
1803 * @param {string} sType the type of event handler
1804 * @param {function} fn the callback to invoke
1805 * @param {boolen} capture capture or bubble phase
1806 * @static
1807 * @private
1809 _simpleRemove: function() {
1810 if (window.removeEventListener) {
1811 return function (el, sType, fn, capture) {
1812 el.removeEventListener(sType, fn, (capture));
1814 } else if (window.detachEvent) {
1815 return function (el, sType, fn) {
1816 el.detachEvent("on" + sType, fn);
1818 } else {
1819 return function(){};
1824 }();
1826 (function() {
1827 var EU = YAHOO.util.Event;
1830 * YAHOO.util.Event.on is an alias for addListener
1831 * @method on
1832 * @see addListener
1833 * @static
1835 EU.on = EU.addListener;
1837 /////////////////////////////////////////////////////////////
1838 // DOMReady
1839 // based on work by: Dean Edwards/John Resig/Matthias Miller
1841 // Internet Explorer: use the readyState of a defered script.
1842 // This isolates what appears to be a safe moment to manipulate
1843 // the DOM prior to when the document's readyState suggests
1844 // it is safe to do so.
1845 if (EU.isIE) {
1847 // Process onAvailable/onContentReady items when when the
1848 // DOM is ready.
1849 YAHOO.util.Event.onDOMReady(
1850 YAHOO.util.Event._tryPreloadAttach,
1851 YAHOO.util.Event, true);
1853 //YAHOO.log("-" + document.readyState + "-");
1855 var el, d=document, b=d.body;
1857 // If the library is being injected after window.onload, it
1858 // is not safe to document.write the script tag. Detecting
1859 // this state doesn't appear possible, so we expect a flag
1860 // in YAHOO_config to be set if the library is being injected.
1861 if (("undefined" !== typeof YAHOO_config) && YAHOO_config.injecting) {
1863 //YAHOO.log("-head-");
1865 //var dr = d.readyState;
1866 //if ("complete" === dr || "interactive" === dr) {
1867 //YAHOO.util.Event._ready();
1868 //YAHOO.util.Event._tryPreloadAttach();
1869 //} else {
1871 el = document.createElement("script");
1872 var p=d.getElementsByTagName("head")[0] || b;
1873 p.insertBefore(el, p.firstChild);
1877 } else {
1878 //YAHOO.log("-dw-");
1879 d.write('<scr'+'ipt id="_yui_eu_dr" defer="true" src="//:"><'+'/script>');
1880 el=document.getElementById("_yui_eu_dr");
1884 if (el) {
1885 el.onreadystatechange = function() {
1886 //YAHOO.log(";comp-" + this.readyState + ";");
1887 if ("complete" === this.readyState) {
1888 this.parentNode.removeChild(this);
1889 YAHOO.util.Event._ready();
1892 } else {
1893 // The library was likely injected into the page
1894 // rendering onDOMReady unreliable
1895 // YAHOO.util.Event._ready();
1898 el=null;
1901 // Safari: The document's readyState in Safari currently will
1902 // change to loaded/complete before images are loaded.
1903 //} else if (EU.webkit) {
1904 } else if (EU.webkit) {
1906 EU._drwatch = setInterval(function(){
1907 var rs=document.readyState;
1908 if ("loaded" == rs || "complete" == rs) {
1909 clearInterval(EU._drwatch);
1910 EU._drwatch = null;
1911 EU._ready();
1913 }, EU.POLL_INTERVAL);
1915 // FireFox and Opera: These browsers provide a event for this
1916 // moment.
1917 } else {
1919 // @todo will this fire when the library is injected?
1921 EU._simpleAdd(document, "DOMContentLoaded", EU._ready);
1924 /////////////////////////////////////////////////////////////
1927 EU._simpleAdd(window, "load", EU._load);
1928 EU._simpleAdd(window, "unload", EU._unload);
1929 EU._tryPreloadAttach();
1930 })();
1934 * EventProvider is designed to be used with YAHOO.augment to wrap
1935 * CustomEvents in an interface that allows events to be subscribed to
1936 * and fired by name. This makes it possible for implementing code to
1937 * subscribe to an event that either has not been created yet, or will
1938 * not be created at all.
1940 * @Class EventProvider
1942 YAHOO.util.EventProvider = function() { };
1944 YAHOO.util.EventProvider.prototype = {
1947 * Private storage of custom events
1948 * @property __yui_events
1949 * @type Object[]
1950 * @private
1952 __yui_events: null,
1955 * Private storage of custom event subscribers
1956 * @property __yui_subscribers
1957 * @type Object[]
1958 * @private
1960 __yui_subscribers: null,
1963 * Subscribe to a CustomEvent by event type
1965 * @method subscribe
1966 * @param p_type {string} the type, or name of the event
1967 * @param p_fn {function} the function to exectute when the event fires
1968 * @param p_obj {Object} An object to be passed along when the event
1969 * fires
1970 * @param p_override {boolean} If true, the obj passed in becomes the
1971 * execution scope of the listener
1973 subscribe: function(p_type, p_fn, p_obj, p_override) {
1975 this.__yui_events = this.__yui_events || {};
1976 var ce = this.__yui_events[p_type];
1978 if (ce) {
1979 ce.subscribe(p_fn, p_obj, p_override);
1980 } else {
1981 this.__yui_subscribers = this.__yui_subscribers || {};
1982 var subs = this.__yui_subscribers;
1983 if (!subs[p_type]) {
1984 subs[p_type] = [];
1986 subs[p_type].push(
1987 { fn: p_fn, obj: p_obj, override: p_override } );
1992 * Unsubscribes one or more listeners the from the specified event
1993 * @method unsubscribe
1994 * @param p_type {string} The type, or name of the event. If the type
1995 * is not specified, it will attempt to remove
1996 * the listener from all hosted events.
1997 * @param p_fn {Function} The subscribed function to unsubscribe, if not
1998 * supplied, all subscribers will be removed.
1999 * @param p_obj {Object} The custom object passed to subscribe. This is
2000 * optional, but if supplied will be used to
2001 * disambiguate multiple listeners that are the same
2002 * (e.g., you subscribe many object using a function
2003 * that lives on the prototype)
2004 * @return {boolean} true if the subscriber was found and detached.
2006 unsubscribe: function(p_type, p_fn, p_obj) {
2007 this.__yui_events = this.__yui_events || {};
2008 var evts = this.__yui_events;
2009 if (p_type) {
2010 var ce = evts[p_type];
2011 if (ce) {
2012 return ce.unsubscribe(p_fn, p_obj);
2014 } else {
2015 for (var i in evts) {
2016 var ret = true;
2017 if (YAHOO.lang.hasOwnProperty(evts, i)) {
2018 ret = ret && evts[i].unsubscribe(p_fn, p_obj);
2021 return ret;
2024 return false;
2028 * Removes all listeners from the specified event. If the event type
2029 * is not specified, all listeners from all hosted custom events will
2030 * be removed.
2031 * @method unsubscribeAll
2032 * @param p_type {string} The type, or name of the event
2034 unsubscribeAll: function(p_type) {
2035 return this.unsubscribe(p_type);
2039 * Creates a new custom event of the specified type. If a custom event
2040 * by that name already exists, it will not be re-created. In either
2041 * case the custom event is returned.
2043 * @method createEvent
2045 * @param p_type {string} the type, or name of the event
2046 * @param p_config {object} optional config params. Valid properties are:
2048 * <ul>
2049 * <li>
2050 * scope: defines the default execution scope. If not defined
2051 * the default scope will be this instance.
2052 * </li>
2053 * <li>
2054 * silent: if true, the custom event will not generate log messages.
2055 * This is false by default.
2056 * </li>
2057 * <li>
2058 * onSubscribeCallback: specifies a callback to execute when the
2059 * event has a new subscriber. This will fire immediately for
2060 * each queued subscriber if any exist prior to the creation of
2061 * the event.
2062 * </li>
2063 * </ul>
2065 * @return {CustomEvent} the custom event
2068 createEvent: function(p_type, p_config) {
2070 this.__yui_events = this.__yui_events || {};
2071 var opts = p_config || {};
2072 var events = this.__yui_events;
2074 if (events[p_type]) {
2075 YAHOO.log("EventProvider createEvent skipped: '"+p_type+"' already exists");
2076 } else {
2078 var scope = opts.scope || this;
2079 var silent = (opts.silent);
2081 var ce = new YAHOO.util.CustomEvent(p_type, scope, silent,
2082 YAHOO.util.CustomEvent.FLAT);
2083 events[p_type] = ce;
2085 if (opts.onSubscribeCallback) {
2086 ce.subscribeEvent.subscribe(opts.onSubscribeCallback);
2089 this.__yui_subscribers = this.__yui_subscribers || {};
2090 var qs = this.__yui_subscribers[p_type];
2092 if (qs) {
2093 for (var i=0; i<qs.length; ++i) {
2094 ce.subscribe(qs[i].fn, qs[i].obj, qs[i].override);
2099 return events[p_type];
2104 * Fire a custom event by name. The callback functions will be executed
2105 * from the scope specified when the event was created, and with the
2106 * following parameters:
2107 * <ul>
2108 * <li>The first argument fire() was executed with</li>
2109 * <li>The custom object (if any) that was passed into the subscribe()
2110 * method</li>
2111 * </ul>
2112 * If the custom event has not been explicitly created, it will be
2113 * created now with the default config, scoped to the host object
2114 * @method fireEvent
2115 * @param p_type {string} the type, or name of the event
2116 * @param arguments {Object*} an arbitrary set of parameters to pass to
2117 * the handler.
2118 * @return {boolean} the return value from CustomEvent.fire
2121 fireEvent: function(p_type, arg1, arg2, etc) {
2123 this.__yui_events = this.__yui_events || {};
2124 var ce = this.__yui_events[p_type];
2126 if (!ce) {
2127 YAHOO.log(p_type + "event fired before it was created.");
2128 return null;
2131 var args = [];
2132 for (var i=1; i<arguments.length; ++i) {
2133 args.push(arguments[i]);
2135 return ce.fire.apply(ce, args);
2139 * Returns true if the custom event of the provided type has been created
2140 * with createEvent.
2141 * @method hasEvent
2142 * @param type {string} the type, or name of the event
2144 hasEvent: function(type) {
2145 if (this.__yui_events) {
2146 if (this.__yui_events[type]) {
2147 return true;
2150 return false;
2156 * KeyListener is a utility that provides an easy interface for listening for
2157 * keydown/keyup events fired against DOM elements.
2158 * @namespace YAHOO.util
2159 * @class KeyListener
2160 * @constructor
2161 * @param {HTMLElement} attachTo The element or element ID to which the key
2162 * event should be attached
2163 * @param {String} attachTo The element or element ID to which the key
2164 * event should be attached
2165 * @param {Object} keyData The object literal representing the key(s)
2166 * to detect. Possible attributes are
2167 * shift(boolean), alt(boolean), ctrl(boolean)
2168 * and keys(either an int or an array of ints
2169 * representing keycodes).
2170 * @param {Function} handler The CustomEvent handler to fire when the
2171 * key event is detected
2172 * @param {Object} handler An object literal representing the handler.
2173 * @param {String} event Optional. The event (keydown or keyup) to
2174 * listen for. Defaults automatically to keydown.
2176 * @knownissue the "keypress" event is completely broken in Safari 2.x and below.
2177 * the workaround is use "keydown" for key listening. However, if
2178 * it is desired to prevent the default behavior of the keystroke,
2179 * that can only be done on the keypress event. This makes key
2180 * handling quite ugly.
2181 * @knownissue keydown is also broken in Safari 2.x and below for the ESC key.
2182 * There currently is no workaround other than choosing another
2183 * key to listen for.
2185 YAHOO.util.KeyListener = function(attachTo, keyData, handler, event) {
2186 if (!attachTo) {
2187 YAHOO.log("No attachTo element specified", "error");
2188 } else if (!keyData) {
2189 YAHOO.log("No keyData specified", "error");
2190 } else if (!handler) {
2191 YAHOO.log("No handler specified", "error");
2194 if (!event) {
2195 event = YAHOO.util.KeyListener.KEYDOWN;
2199 * The CustomEvent fired internally when a key is pressed
2200 * @event keyEvent
2201 * @private
2202 * @param {Object} keyData The object literal representing the key(s) to
2203 * detect. Possible attributes are shift(boolean),
2204 * alt(boolean), ctrl(boolean) and keys(either an
2205 * int or an array of ints representing keycodes).
2207 var keyEvent = new YAHOO.util.CustomEvent("keyPressed");
2210 * The CustomEvent fired when the KeyListener is enabled via the enable()
2211 * function
2212 * @event enabledEvent
2213 * @param {Object} keyData The object literal representing the key(s) to
2214 * detect. Possible attributes are shift(boolean),
2215 * alt(boolean), ctrl(boolean) and keys(either an
2216 * int or an array of ints representing keycodes).
2218 this.enabledEvent = new YAHOO.util.CustomEvent("enabled");
2221 * The CustomEvent fired when the KeyListener is disabled via the
2222 * disable() function
2223 * @event disabledEvent
2224 * @param {Object} keyData The object literal representing the key(s) to
2225 * detect. Possible attributes are shift(boolean),
2226 * alt(boolean), ctrl(boolean) and keys(either an
2227 * int or an array of ints representing keycodes).
2229 this.disabledEvent = new YAHOO.util.CustomEvent("disabled");
2231 if (typeof attachTo == 'string') {
2232 attachTo = document.getElementById(attachTo);
2235 if (typeof handler == 'function') {
2236 keyEvent.subscribe(handler);
2237 } else {
2238 keyEvent.subscribe(handler.fn, handler.scope, handler.correctScope);
2242 * Handles the key event when a key is pressed.
2243 * @method handleKeyPress
2244 * @param {DOMEvent} e The keypress DOM event
2245 * @param {Object} obj The DOM event scope object
2246 * @private
2248 function handleKeyPress(e, obj) {
2249 if (! keyData.shift) {
2250 keyData.shift = false;
2252 if (! keyData.alt) {
2253 keyData.alt = false;
2255 if (! keyData.ctrl) {
2256 keyData.ctrl = false;
2259 // check held down modifying keys first
2260 if (e.shiftKey == keyData.shift &&
2261 e.altKey == keyData.alt &&
2262 e.ctrlKey == keyData.ctrl) { // if we pass this, all modifiers match
2264 var dataItem;
2265 var keyPressed;
2267 if (keyData.keys instanceof Array) {
2268 for (var i=0;i<keyData.keys.length;i++) {
2269 dataItem = keyData.keys[i];
2271 if (dataItem == e.charCode ) {
2272 keyEvent.fire(e.charCode, e);
2273 break;
2274 } else if (dataItem == e.keyCode) {
2275 keyEvent.fire(e.keyCode, e);
2276 break;
2279 } else {
2280 dataItem = keyData.keys;
2281 if (dataItem == e.charCode ) {
2282 keyEvent.fire(e.charCode, e);
2283 } else if (dataItem == e.keyCode) {
2284 keyEvent.fire(e.keyCode, e);
2291 * Enables the KeyListener by attaching the DOM event listeners to the
2292 * target DOM element
2293 * @method enable
2295 this.enable = function() {
2296 if (! this.enabled) {
2297 YAHOO.util.Event.addListener(attachTo, event, handleKeyPress);
2298 this.enabledEvent.fire(keyData);
2301 * Boolean indicating the enabled/disabled state of the Tooltip
2302 * @property enabled
2303 * @type Boolean
2305 this.enabled = true;
2309 * Disables the KeyListener by removing the DOM event listeners from the
2310 * target DOM element
2311 * @method disable
2313 this.disable = function() {
2314 if (this.enabled) {
2315 YAHOO.util.Event.removeListener(attachTo, event, handleKeyPress);
2316 this.disabledEvent.fire(keyData);
2318 this.enabled = false;
2322 * Returns a String representation of the object.
2323 * @method toString
2324 * @return {String} The string representation of the KeyListener
2326 this.toString = function() {
2327 return "KeyListener [" + keyData.keys + "] " + attachTo.tagName +
2328 (attachTo.id ? "[" + attachTo.id + "]" : "");
2334 * Constant representing the DOM "keydown" event.
2335 * @property YAHOO.util.KeyListener.KEYDOWN
2336 * @static
2337 * @final
2338 * @type String
2340 YAHOO.util.KeyListener.KEYDOWN = "keydown";
2343 * Constant representing the DOM "keyup" event.
2344 * @property YAHOO.util.KeyListener.KEYUP
2345 * @static
2346 * @final
2347 * @type String
2349 YAHOO.util.KeyListener.KEYUP = "keyup";
2350 YAHOO.register("event", YAHOO.util.Event, {version: "2.3.0", build: "442"});