2 Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
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
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
27 YAHOO
.util
.CustomEvent = function(type
, oScope
, silent
, signature
) {
30 * The type of event, returned to subscribers when the event fires
37 * The scope the the event will fire from by default. Defaults to the window
42 this.scope
= oScope
|| window
;
45 * By default all custom events are logged in the debug build, set silent
46 * to true to disable debug outpu for this event.
53 * Custom events support two styles of arguments provided to the event
56 * <li>YAHOO.util.CustomEvent.LIST:
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>
63 * <li>YAHOO.util.CustomEvent.FLAT
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>
74 this.signature
= signature
|| YAHOO
.util
.CustomEvent
.LIST
;
77 * The subscribers to this event
78 * @property subscribers
81 this.subscribers
= [];
84 YAHOO
.log( "Creating " + this, "info", "Event" );
87 var onsubscribeType
= "_YUICEOnSubscribe";
89 // Only add subscribe events for events that are not generated by
91 if (type
!== onsubscribeType
) {
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
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
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
129 * @property YAHOO.util.CustomEvent.FLAT
133 YAHOO
.util
.CustomEvent
.FLAT
= 1;
135 YAHOO
.util
.CustomEvent
.prototype = {
138 * Subscribes the caller to this event
140 * @param {Function} fn The function to execute
141 * @param {Object} obj An object to be passed along when the event
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
) {
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
) {
176 return this.unsubscribeAll();
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
)) {
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:
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()
202 * @param {Object*} arguments an arbitrary set of parameters to pass to
204 * @return {boolean} false if one of the subscribers returned false,
208 var len
=this.subscribers
.length
;
209 if (!len
&& this.silent
) {
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
;
222 YAHOO
.log( "Firing " + this + ", " +
223 "args: " + args
+ ", " +
224 "subscribers: " + len
,
228 for (i
=0; i
<len
; ++i
) {
229 var s
= this.subscribers
[i
];
234 YAHOO
.log( this.type
+ "->" + (i
+1) + ": " + s
,
238 var scope
= s
.getScope(this.scope
);
240 if (this.signature
== YAHOO
.util
.CustomEvent
.FLAT
) {
242 if (args
.length
> 0) {
245 ret
= s
.fn
.call(scope
, param
, s
.obj
);
247 ret
= s
.fn
.call(scope
, this.type
, args
, s
.obj
);
251 YAHOO
.log("Event cancelled, subscriber " + i
+
252 " of " + len
, "info", "Event");
262 var newlist
=[],subs
=this.subscribers
;
263 for (i
=0,len
=subs
.length
; i
<len
; ++i
) {
265 newlist
.push(subs
[i
]);
268 this.subscribers
=newlist
;
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
);
293 _delete: function(index
) {
294 var s
= this.subscribers
[index
];
300 this.subscribers
[index
]=null;
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
324 YAHOO
.util
.Subscriber = function(fn
, obj
, override
) {
327 * The callback that will be execute when the event fires
334 * An optional custom object that will passed to the callback when
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.
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.
359 * @param {Object} defaultScope the scope to use if this listener does not
362 YAHOO
.util
.Subscriber
.prototype.getScope = function(defaultScope
) {
364 if (this.override
=== true) {
367 return this.override
;
374 * Returns true if the fn and obj match this objects properties.
375 * Used by the unsubscribe method to match the right subscriber.
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
) {
385 return (this.fn
== fn
&& this.obj
== obj
);
387 return (this.fn
== fn
);
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
404 * @title Event Utility
405 * @namespace YAHOO.util
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.
423 YAHOO
.util
.Event = function() {
426 * True after the onload event has fired
427 * @property loadComplete
432 var loadComplete
= false;
435 * True when the document is initially usable
441 var DOMReady
= false;
444 * Cache of wrapped listeners
445 * @property listeners
453 * User-defined unload function that will be fired before all events
455 * @property unloadListeners
460 var unloadListeners
= [];
463 * Cache of DOM0 event handlers to work around issues with DOM2 events
465 * @property legacyEvents
469 var legacyEvents
= [];
472 * Listener stack for DOM0 events
473 * @property legacyHandlers
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
483 * @property retryCount
490 * onAvailable listeners
491 * @property onAvailStack
495 var onAvailStack
= [];
498 * Lookup table for legacy events
499 * @property legacyMap
506 * Counter for auto id generation
514 * Normalized keycodes for webkit/safari
515 * @property webkitKeymap
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
544 * The poll interval in milliseconds
545 * @property POLL_INTERVAL
553 * Element to bind, int constant
562 * Type of event, int constant
571 * Function to execute, int constant
580 * Function wrapped for scope correction and cleanup, int constant
589 * Object passed in by the user that will be returned as a
590 * parameter to the callback, int constant
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
609 * addListener/removeListener can throw errors in unexpected scenarios.
610 * These errors are suppressed, the method returns false, and this property
612 * @property lastError
623 * @deprecated use YAHOO.env.ua.webkit
625 isSafari
: YAHOO
.env
.ua
.webkit
,
633 * @deprecated use YAHOO.env.ua.webkit
635 webkit
: YAHOO
.env
.ua
.webkit
,
642 * @deprecated use YAHOO.env.ua.ie
644 isIE
: YAHOO
.env
.ua
.ie
,
648 * @property _interval
655 * @method startInterval
659 startInterval: function() {
660 if (!this._interval
) {
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
690 onAvailable: function(p_id
, p_fn
, p_obj
, p_override
) {
691 onAvailStack
.push( { id
: p_id
,
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
718 * <p>"DOMReady", [], obj</p>
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
732 onDOMReady: function(p_fn
, p_obj
, p_override
) {
734 setTimeout(function() {
737 if (p_override
=== true) {
743 p_fn
.call(s
, "DOMReady", [], p_obj
);
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
770 onContentReady: function(p_id
, p_fn
, p_obj
, p_override
) {
771 onAvailStack
.push( { id
: p_id
,
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
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
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.
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");
811 // The el argument can be an array of elements or element ids.
812 if ( this._isValidCollection(el
)) {
814 for (var i
=0,len
=el
.length
; i
<len
; ++i
) {
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.
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
);
844 // Element should be an html element or an array if we get
847 // this.logger.debug("unable to attach event " + sType);
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
];
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
868 if (override
=== true) {
875 // wrap the function so we can return the obj object when
877 var wrappedFn = function(e
) {
878 return fn
.call(scope
, YAHOO
.util
.Event
.getEvent(e
),
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
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
] = [];
906 YAHOO
.util
.Event
.fireLegacyEvent(
907 YAHOO
.util
.Event
.getEvent(e
), legacyIndex
);
911 // add a reference to the wrapped listener to our custom
913 //legacyHandlers[legacyIndex].push(index);
914 legacyHandlers
[legacyIndex
].push(li
);
918 this._simpleAdd(el
, sType
, wrappedFn
, false);
920 // handle an error trying to attach an event. If it fails
921 // we need to clean up the cache
923 this.removeListener(el
, sType
, fn
);
933 * When using legacy events, the handler is routed to this object
934 * so we can fire our custom listener stack.
935 * @method fireLegacyEvent
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
) {
946 if ( li
&& li
[this.WFN
] ) {
947 scope
= li
[this.ADJ_SCOPE
];
948 ret
= li
[this.WFN
].call(scope
, e
);
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
957 le
= legacyEvents
[legacyIndex
];
966 * Returns the legacy event index that matches the supplied
968 * @method getLegacyIndex
972 getLegacyIndex: function(el
, sType
) {
973 var key
= this.generateId(el
) + sType
;
974 if (typeof legacyMap
[key
] == "undefined") {
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
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) {
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
1011 * @return {boolean} true if the unbind was successful, false
1015 removeListener: function(el
, sType
, fn
) {
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
)) {
1024 for (i
=0,len
=el
.length
; i
<len
; ++i
) {
1025 ok
= ( this.removeListener(el
[i
], sType
, fn
) && ok
);
1030 if (!fn
|| !fn
.call
) {
1031 // this.logger.debug("Error, function is not valid " + fn);
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
];
1044 //unloadListeners.splice(i, 1);
1045 unloadListeners
[i
]=null;
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
);
1065 cacheItem
= listeners
[index
];
1068 if (!el
|| !cacheItem
) {
1069 // this.logger.debug("cached listener not found");
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
];
1079 for (i
=0, len
=llist
.length
; i
<len
; ++i
) {
1082 li
[this.EL
] == el
&&
1083 li
[this.TYPE
] == sType
&&
1084 li
[this.FN
] == fn
) {
1085 //llist.splice(i, 1);
1094 this._simpleRemove(el
, sType
, cacheItem
[this.WFN
], false);
1096 this.lastError
= ex
;
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;
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.
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
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
1138 resolveTextNode: function(node
) {
1139 if (node
&& 3 == node
.nodeType
) {
1140 return node
.parentNode
;
1147 * Returns the event's pageX
1149 * @param {Event} ev the event
1150 * @return {int} the event's pageX
1153 getPageX: function(ev
) {
1155 if (!x
&& 0 !== x
) {
1156 x
= ev
.clientX
|| 0;
1159 x
+= this._getScrollLeft();
1167 * Returns the event's pageY
1169 * @param {Event} ev the event
1170 * @return {int} the event's pageY
1173 getPageY: function(ev
) {
1175 if (!y
&& 0 !== y
) {
1176 y
= ev
.clientY
|| 0;
1179 y
+= this._getScrollTop();
1188 * Returns the pageX and pageY properties as an indexed array.
1190 * @param {Event} ev the event
1191 * @return {[x, y]} the pageX and pageY properties of the event
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
1205 getRelatedTarget: function(ev
) {
1206 var t
= ev
.relatedTarget
;
1208 if (ev
.type
== "mouseout") {
1210 } else if (ev
.type
== "mouseover") {
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.
1222 * @param {Event} ev the event
1223 * @return {Date} the time of the event
1226 getTime: function(ev
) {
1228 var t
= new Date().getTime();
1232 this.lastError
= ex
;
1241 * Convenience method for stopPropagation + preventDefault
1243 * @param {Event} ev the event
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
1257 stopPropagation: function(ev
) {
1258 if (ev
.stopPropagation
) {
1259 ev
.stopPropagation();
1261 ev
.cancelBubble
= true;
1266 * Prevents the default behavior of the event
1267 * @method preventDefault
1268 * @param {Event} ev the event
1271 preventDefault: function(ev
) {
1272 if (ev
.preventDefault
) {
1273 ev
.preventDefault();
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.
1286 * @param {Event} e the event parameter from the handler
1287 * @return {Event} the event
1290 getEvent: function(e
) {
1291 var ev
= e
|| window
.event
;
1294 var c
= this.getEvent
.caller
;
1296 ev
= c
.arguments
[0];
1297 if (ev
&& Event
== ev
.constructor) {
1308 * Returns the charcode for an event
1309 * @method getCharCode
1310 * @param {Event} ev the event
1311 * @return {int} the event's charCode
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
];
1325 * Locating the saved event handler data by function ref
1327 * @method _getCacheIndex
1331 _getCacheIndex: function(el
, sType
, fn
) {
1332 for (var i
=0,len
=listeners
.length
; i
<len
; ++i
) {
1333 var li
= listeners
[i
];
1335 li
[this.FN
] == fn
&&
1336 li
[this.EL
] == el
&&
1337 li
[this.TYPE
] == sType
) {
1346 * Generates an unique ID for the element if it does not already
1348 * @method generateId
1349 * @param el the element to create the id for
1350 * @return {string} the resulting id of the element
1353 generateId: function(el
) {
1357 id
= "yuievtautoid-" + counter
;
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
1378 _isValidCollection: function(o
) {
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" );
1387 YAHOO
.log("_isValidCollection threw an error, assuming that " +
1388 " this is a cross frame problem and not a collection", warn
);
1399 * @deprecated Elements are not cached due to issues that arise when
1400 * elements are removed and re-added
1405 * We cache elements bound by id because when the unload event
1406 * fires, we can no longer use document.getElementById
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
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
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
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.
1455 //EU._simpleRemove(window, "load", EU._load);
1461 * Fires the DOMReady event listeners the first time the document is
1467 _ready: function(e
) {
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
1484 * @method _tryPreloadAttach
1488 _tryPreloadAttach: function() {
1495 // Hold off if DOMReady has not fired and check current
1496 // readyState to protect against the IE operation aborted
1498 //if (!DOMReady || "complete" !== document.readyState) {
1500 this.startInterval();
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
;
1515 tryAgain
= (retryCount
> 0);
1521 var executeItem = function (el
, item
) {
1523 if (item
.override
) {
1524 if (item
.override
=== true) {
1527 scope
= item
.override
;
1530 item
.fn
.call(scope
, item
.obj
);
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
);
1541 executeItem(el
, item
);
1542 onAvailStack
[i
] = null;
1544 notAvail
.push(item
);
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
);
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;
1563 notAvail
.push(item
);
1568 retryCount
= (notAvail
.length
=== 0) ? 0 : retryCount
- 1;
1571 // we may need to strip the nulled out items here
1572 this.startInterval();
1574 clearInterval(this._interval
);
1575 this._interval
= null;
1578 this.locked
= false;
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
1596 purgeElement: function(el
, recurse
, sType
) {
1597 var elListeners
= this.getListeners(el
, sType
);
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 * type: (string) the type of event
1623 * fn: (function) the callback supplied to addListener
1624 * obj: (object) the custom object supplied to addListener
1625 * adjust: (boolean) whether or not to adjust the default scope
1626 * index: (int) its position in the Event util listener cache
1629 getListeners: function(el
, sType
) {
1630 var results
=[], searchLists
;
1632 searchLists
= [listeners
, unloadListeners
];
1633 } else if (sType
== "unload") {
1634 searchLists
= [unloadListeners
];
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
]) ) {
1650 adjust
: l
[this.ADJ_SCOPE
],
1658 return (results
.length
) ? results
: null;
1662 * Removes all listeners registered by pe.event. Called
1663 * automatically during the unload event.
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
];
1676 if (l
[EU
.ADJ_SCOPE
]) {
1677 if (l
[EU
.ADJ_SCOPE
] === true) {
1680 scope
= l
[EU
.ADJ_SCOPE
];
1683 l
[EU
.FN
].call(scope
, EU
.getEvent(e
), l
[EU
.OBJ
] );
1684 unloadListeners
[i
] = null;
1690 unloadListeners
= null;
1692 if (listeners
&& listeners
.length
> 0) {
1693 j
= listeners
.length
;
1696 l
= listeners
[index
];
1698 EU
.removeListener(l
[EU
.EL
], l
[EU
.TYPE
], l
[EU
.FN
], index
);
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
1729 _getScrollLeft: function() {
1730 return this._getScroll()[1];
1735 * @method _getScrollTop
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
1750 _getScroll: function() {
1751 var dd
= document
.documentElement
, db
= document
.body
;
1752 if (dd
&& (dd
.scrollTop
|| dd
.scrollLeft
)) {
1753 return [dd
.scrollTop
, dd
.scrollLeft
];
1755 return [db
.scrollTop
, db
.scrollLeft
];
1762 * Used by old versions of CustomEvent, restored for backwards
1767 * @deprecated still here for backwards compatibility
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
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
);
1794 return function(){};
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
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
);
1819 return function(){};
1827 var EU
= YAHOO
.util
.Event
;
1830 * YAHOO.util.Event.on is an alias for addListener
1835 EU
.on
= EU
.addListener
;
1837 /////////////////////////////////////////////////////////////
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.
1847 // Process onAvailable/onContentReady items when when the
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();
1871 el
= document
.createElement("script");
1872 var p
=d
.getElementsByTagName("head")[0] || b
;
1873 p
.insertBefore(el
, p
.firstChild
);
1878 //YAHOO.log("-dw-");
1879 d
.write('<scr'+'ipt id="_yui_eu_dr" defer="true" src="//:"><'+'/script>');
1880 el
=document
.getElementById("_yui_eu_dr");
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();
1893 // The library was likely injected into the page
1894 // rendering onDOMReady unreliable
1895 // YAHOO.util.Event._ready();
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
);
1913 }, EU
.POLL_INTERVAL
);
1915 // FireFox and Opera: These browsers provide a event for this
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();
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
1955 * Private storage of custom event subscribers
1956 * @property __yui_subscribers
1960 __yui_subscribers
: null,
1963 * Subscribe to a CustomEvent by event type
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
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
];
1979 ce
.subscribe(p_fn
, p_obj
, p_override
);
1981 this.__yui_subscribers
= this.__yui_subscribers
|| {};
1982 var subs
= this.__yui_subscribers
;
1983 if (!subs
[p_type
]) {
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
;
2010 var ce
= evts
[p_type
];
2012 return ce
.unsubscribe(p_fn
, p_obj
);
2015 for (var i
in evts
) {
2017 if (YAHOO
.lang
.hasOwnProperty(evts
, i
)) {
2018 ret
= ret
&& evts
[i
].unsubscribe(p_fn
, p_obj
);
2028 * Removes all listeners from the specified event. If the event type
2029 * is not specified, all listeners from all hosted custom events will
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:
2050 * scope: defines the default execution scope. If not defined
2051 * the default scope will be this instance.
2054 * silent: if true, the custom event will not generate log messages.
2055 * This is false by default.
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
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");
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
];
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:
2108 * <li>The first argument fire() was executed with</li>
2109 * <li>The custom object (if any) that was passed into the subscribe()
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
2115 * @param p_type {string} the type, or name of the event
2116 * @param arguments {Object*} an arbitrary set of parameters to pass to
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
];
2127 YAHOO
.log(p_type
+ "event fired before it was created.");
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
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
]) {
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
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
) {
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");
2195 event
= YAHOO
.util
.KeyListener
.KEYDOWN
;
2199 * The CustomEvent fired internally when a key is pressed
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()
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
);
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
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
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
);
2274 } else if (dataItem
== e
.keyCode
) {
2275 keyEvent
.fire(e
.keyCode
, e
);
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
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
2305 this.enabled
= true;
2309 * Disables the KeyListener by removing the DOM event listeners from the
2310 * target DOM element
2313 this.disable = function() {
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.
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
2340 YAHOO
.util
.KeyListener
.KEYDOWN
= "keydown";
2343 * Constant representing the DOM "keyup" event.
2344 * @property YAHOO.util.KeyListener.KEYUP
2349 YAHOO
.util
.KeyListener
.KEYUP
= "keyup";
2350 YAHOO
.register("event", YAHOO
.util
.Event
, {version
: "2.3.0", build
: "442"});