2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
9 * DOM event listener abstraction layer
11 * @submodule event-base
17 // Unlike most of the library, this code has to be executed as soon as it is
18 // introduced into the page -- and it should only be executed one time
19 // regardless of the number of instances that use it.
21 var GLOBAL_ENV = YUI.Env,
27 POLL_INTERVAL = C.pollInterval || 40,
29 _ready = function(e) {
33 if (!GLOBAL_ENV._ready) {
35 GLOBAL_ENV._ready = function() {
36 if (!GLOBAL_ENV.DOMReady) {
37 GLOBAL_ENV.DOMReady=true;
39 // Remove the DOMContentLoaded (FF/Opera/Safari)
40 if (D.removeEventListener) {
41 D.removeEventListener("DOMContentLoaded", _ready, false);
46 // create custom event
48 /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */
50 // Internet Explorer: use the readyState of a defered script.
51 // This isolates what appears to be a safe moment to manipulate
52 // the DOM prior to when the document's readyState suggests
53 // it is safe to do so.
54 if (navigator.userAgent.match(/MSIE/)) {
56 if (self !== self.top) {
57 document.onreadystatechange = function() {
58 if (document.readyState == 'complete') {
59 document.onreadystatechange = null;
65 GLOBAL_ENV._dri = setInterval(function() {
67 // throws an error if doc is not ready
68 document.documentElement.doScroll('left');
69 clearInterval(GLOBAL_ENV._dri);
70 GLOBAL_ENV._dri = null;
77 // FireFox, Opera, Safari 3+: These browsers provide a event for this
80 D.addEventListener("DOMContentLoaded", _ready, false);
83 /////////////////////////////////////////////////////////////
87 YUI.add('event-base', function(Y) {
91 * DOM event listener abstraction layer
93 * @submodule event-base
96 var GLOBAL_ENV = YUI.Env,
102 Y.publish('domready', {
106 if (GLOBAL_ENV.DOMReady) {
107 // console.log('DOMReady already fired', 'info', 'event');
110 // console.log('setting up before listener', 'info', 'event');
111 // console.log('env: ' + YUI.Env.windowLoaded, 'info', 'event');
112 Y.before(yready, GLOBAL_ENV, "_ready");
119 * Custom event engine, DOM event listener abstraction layer, synthetic DOM
122 * @submodule event-base
126 * Wraps a DOM event, properties requiring browser abstraction are
127 * fixed here. Provids a security layer when required.
128 * @class DOMEventFacade
129 * @param ev {Event} the DOM event
130 * @param currentTarget {HTMLElement} the element the listener was attached to
131 * @param wrapper {Event.Custom} the custom event wrapper for this DOM event
135 * @TODO constants? LEFTBUTTON, MIDDLEBUTTON, RIGHTBUTTON, keys
142 // "button" : 1, // we supply
143 // "bubbles" : 1, // needed?
144 // "cancelable" : 1, // needed?
145 // "charCode" : 1, // we supply
147 // "currentTarget" : 1, // we supply
149 clientX : 1, // needed?
150 clientY : 1, // needed?
151 detail : 1, // not fully implemented
152 // "fromElement" : 1,
154 // "height" : 1, // needed?
155 // "initEvent" : 1, // need the init events?
156 // "initMouseEvent" : 1,
157 // "initUIEvent" : 1,
158 // "layerX" : 1, // needed?
159 // "layerY" : 1, // needed?
161 // "modifiers" : 1, // needed?
162 // "offsetX" : 1, // needed?
163 // "offsetY" : 1, // needed?
164 // "preventDefault" : 1, // we supply
165 // "reason" : 1, // IE proprietary
166 // "relatedTarget" : 1,
167 // "returnValue" : 1, // needed?
169 // "srcUrn" : 1, // IE proprietary
171 // "srcFilter" : 1, IE proprietary
172 // "stopPropagation" : 1, // we supply
174 // "timeStamp" : 1, // needed?
178 // "which" : 1, // we supply
179 // "width" : 1, // needed?
189 * webkit key remapping required for Safari < 3.1
190 * @property webkitKeymap
198 63276: 33, // page up
199 63277: 34, // page down
200 25: 9, // SHIFT-TAB (Safari provides a different key code in
201 // this case, even though the shiftKey modifier is set)
208 * Returns a wrapped node. Intended to be used on event targets,
209 * so it will return the node's parent if the target is a text
212 * If accessing a property of the node throws an error, this is
213 * probably the anonymous div wrapper Gecko adds inside text
214 * nodes. This likely will only occur when attempting to access
215 * the relatedTarget. In this case, we now return null because
216 * the anonymous div is completely useless and we do not know
217 * what the related target was because we can't even get to
218 * the element's parent node.
223 resolve = function(n) {
225 if (n && 3 == n.nodeType) {
236 // provide a single event with browser abstractions resolved
238 // include all properties for both browers?
239 // include only DOM2 spec properties?
240 // provide browser-specific facade?
242 Y.DOMEventFacade = function(ev, currentTarget, wrapper) {
244 wrapper = wrapper || {};
246 var e = ev, ot = currentTarget, d = Y.config.doc, b = d.body,
247 x = e.pageX, y = e.pageY, c, t;
249 this.altKey = e.altKey;
250 this.ctrlKey = e.ctrlKey;
251 this.metaKey = e.metaKey;
252 this.shiftKey = e.shiftKey;
254 this.clientX = e.clientX;
255 this.clientY = e.clientY;
257 //////////////////////////////////////////////////////
264 x += Math.max(d.documentElement.scrollLeft, b.scrollLeft);
265 y += Math.max(d.documentElement.scrollTop, b.scrollTop);
269 this._yuifacade = true;
278 * The X location of the event on the page (including scroll)
285 * The Y location of the event on the page (including scroll)
291 //////////////////////////////////////////////////////
293 c = e.keyCode || e.charCode || 0;
295 if (ua.webkit && (c in webkitKeymap)) {
300 * The keyCode for key events. Uses charCode if keyCode is not available
307 * The charCode for key events. Same as keyCode
313 //////////////////////////////////////////////////////
316 * The button that was pushed.
320 this.button = e.which || e.button;
323 * The button that was pushed. Same as button.
327 this.which = this.button;
329 //////////////////////////////////////////////////////
332 * Node reference for the targeted element
336 this.target = resolve(e.target || e.srcElement);
339 * Node reference for the element that the listener was attached to.
340 * @propery currentTarget
343 this.currentTarget = resolve(ot);
348 if (e.type == "mouseout") {
350 } else if (e.type == "mouseover") {
356 * Node reference to the relatedTarget
357 * @propery relatedTarget
360 this.relatedTarget = resolve(t);
363 * Number representing the direction and velocity of the movement of the mousewheel.
364 * Negative is down, the higher the number, the faster. Applies to the mousewheel event.
365 * @property wheelDelta
368 if (e.type == "mousewheel" || e.type == "DOMMouseScroll") {
369 this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1);
372 //////////////////////////////////////////////////////
376 * Stops the propagation to the next bubble target
377 * @method stopPropagation
379 this.stopPropagation = function() {
380 if (e.stopPropagation) {
383 e.cancelBubble = true;
389 * Stops the propagation to the next bubble target and
390 * prevents any additional listeners from being exectued
391 * on the current target.
392 * @method stopImmediatePropagation
394 this.stopImmediatePropagation = function() {
395 if (e.stopImmediatePropagation) {
396 e.stopImmediatePropagation();
398 this.stopPropagation();
404 * Prevents the event's default behavior
405 * @method preventDefault
406 * @param returnValue {string} sets the returnValue of the event to this value
407 * (rather than the default false value). This can be used to add a customized
408 * confirmation query to the beforeunload event).
410 this.preventDefault = function(returnValue) {
411 if (e.preventDefault) {
414 e.returnValue = returnValue || false;
415 wrapper.prevented = 1;
419 * Stops the event propagation and prevents the default
422 * @param immediate {boolean} if true additional listeners
423 * on the current target will not be executed
425 this.halt = function(immediate) {
427 this.stopImmediatePropagation();
429 this.stopPropagation();
432 this.preventDefault();
440 * DOM event listener abstraction layer
442 * @submodule event-base
446 * The event utility provides functions to add and remove event listeners,
447 * event cleansing. It also tries to automatically remove listeners it
448 * registers during the unload event.
454 Y.Env.evt.dom_wrappers = {};
455 Y.Env.evt.dom_map = {};
457 var _eventenv = Y.Env.evt,
459 remove = YUI.Env.remove,
461 onLoad = function() {
462 YUI.Env.windowLoaded = true;
464 remove(window, "load", onLoad);
467 onUnload = function() {
469 remove(window, "unload", onUnload);
472 EVENT_READY = 'domready',
474 COMPAT_ARG = '~yui|2|compat~',
476 shouldIterate = function(o) {
478 return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !o.alert);
488 * True after the onload event has fired
489 * @property _loadComplete
494 var _loadComplete = false,
497 * The number of times to poll after window.onload. This number is
498 * increased if additional late-bound handlers are requested after
500 * @property _retryCount
507 * onAvailable listeners
515 * Custom event wrappers for DOM events. Key is
516 * 'event:' + Element uid stamp + event type
517 * @property _wrappers
518 * @type Y.Event.Custom
522 _wrappers = _eventenv.dom_wrappers,
524 _windowLoadKey = null,
527 * Custom event wrapper map DOM events. Key is
528 * Element uid stamp. Each item is a hash of custom event
529 * wrappers as provided in the _wrappers collection. This
530 * provides the infrastructure for getListeners.
531 * @property _el_events
535 _el_events = _eventenv.dom_map;
540 * The number of times we should look for elements that are not
541 * in the DOM at the time the event is requested after the document
542 * has been loaded. The default is 1000@amp;40 ms, so it will poll
543 * for 40 seconds or until all outstanding handlers are bound
544 * (whichever comes first).
545 * @property POLL_RETRYS
553 * The poll interval in milliseconds
554 * @property POLL_INTERVAL
562 * addListener/removeListener can throw errors in unexpected scenarios.
563 * These errors are suppressed, the method returns false, and this property
565 * @property lastError
574 * @property _interval
581 * document readystate poll handle
589 * True when the document is initially usable
597 * @method startInterval
601 startInterval: function() {
605 E._interval = setInterval(Y.bind(E._poll, E), E.POLL_INTERVAL);
610 * Executes the supplied callback when the item with the supplied
611 * id is found. This is meant to be used to execute behavior as
612 * soon as possible as the page loads. If you use this after the
613 * initial page load it will poll for a fixed time for the element.
614 * The number of times it will poll and the frequency are
615 * configurable. By default it will poll for 10 seconds.
617 * <p>The callback is executed with a single parameter:
618 * the custom object parameter, if provided.</p>
620 * @method onAvailable
622 * @param {string||string[]} id the id of the element, or an array
623 * of ids to look for.
624 * @param {function} fn what to execute when the element is found.
625 * @param {object} p_obj an optional object to be passed back as
627 * @param {boolean|object} p_override If set to true, fn will execute
628 * in the context of p_obj, if set to an object it
629 * will execute in the context of that object
630 * @param checkContent {boolean} check child node readiness (onContentReady)
632 * @deprecated Use Y.on("available")
634 // @TODO fix arguments
635 onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) {
637 var a = Y.Array(id), i, availHandle;
640 for (i=0; i<a.length; i=i+1) {
645 override: p_override,
646 checkReady: checkContent,
650 _retryCount = this.POLL_RETRYS;
652 // We want the first test to be immediate, but async
653 setTimeout(Y.bind(Y.Event._poll, Y.Event), 0);
655 availHandle = new Y.EventHandle({
657 _delete: function() {
658 // set by the event system for lazy DOM listeners
659 if (availHandle.handle) {
660 availHandle.handle.detach();
666 // otherwise try to remove the onAvailable listener(s)
667 for (i = 0; i < a.length; i++) {
668 for (j = 0; j < _avail.length; j++) {
669 if (a[i] === _avail[j].id) {
682 * Works the same way as onAvailable, but additionally checks the
683 * state of sibling elements to determine if the content of the
684 * available element is safe to modify.
686 * <p>The callback is executed with a single parameter:
687 * the custom object parameter, if provided.</p>
689 * @method onContentReady
691 * @param {string} id the id of the element to look for.
692 * @param {function} fn what to execute when the element is ready.
693 * @param {object} p_obj an optional object to be passed back as
695 * @param {boolean|object} p_override If set to true, fn will execute
696 * in the context of p_obj. If an object, fn will
697 * exectute in the context of that object
700 * @deprecated Use Y.on("contentready")
702 // @TODO fix arguments
703 onContentReady: function(id, fn, p_obj, p_override, compat) {
704 return this.onAvailable(id, fn, p_obj, p_override, true, compat);
708 * Adds an event listener
712 * @param {String} type The type of event to append
713 * @param {Function} fn The method the event invokes
714 * @param {String|HTMLElement|Array|NodeList} el An id, an element
715 * reference, or a collection of ids and/or elements to assign the
717 * @param {Object} context optional context object
718 * @param {Boolean|object} args 0..n arguments to pass to the callback
719 * @return {EventHandle} an object to that can be used to detach the listener
724 attach: function(type, fn, el, context) {
725 return Y.Event._attach(Y.Array(arguments, 0, true));
728 _createWrapper: function (el, type, capture, compat, facade) {
730 var ek = Y.stamp(el),
731 key = 'event:' + ek + type,
735 if (false === facade) {
743 cewrapper = _wrappers[key];
748 cewrapper = Y.publish(key, {
751 contextFn: function() {
752 cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el);
753 return cewrapper.nodeRef;
757 // for later removeListener calls
760 cewrapper.domkey = ek;
761 cewrapper.type = type;
762 cewrapper.fn = function(e) {
763 cewrapper.fire(Y.Event.getEvent(e, el, (compat || (false === facade))));
765 cewrapper.capture = capture;
767 if (el == Y.config.win && type == "load") {
768 // window load happens once
769 cewrapper.fireOnce = true;
770 _windowLoadKey = key;
773 _wrappers[key] = cewrapper;
774 _el_events[ek] = _el_events[ek] || {};
775 _el_events[ek][key] = cewrapper;
777 add(el, type, cewrapper.fn, capture);
784 _attach: function(args, config) {
786 var compat, E=Y.Event,
787 handles, oEl, cewrapper, context,
788 fireNow = false, ret,
791 el = args[2] || Y.config.win,
792 facade = config && config.facade,
793 capture = config && config.capture;
795 if (args[args.length-1] === COMPAT_ARG) {
797 // trimmedArgs.pop();
800 if (!fn || !fn.call) {
801 // throw new TypeError(type + " attach call failed, callback undefined");
805 // The el argument can be an array of elements or element ids.
806 if (shouldIterate(el)) {
810 Y.each(el, function(v, k) {
812 handles.push(E._attach(args, config));
815 // return (handles.length === 1) ? handles[0] : handles;
816 return new Y.EventHandle(handles);
818 // If the el argument is a string, we assume it is
819 // actually the id of the element. If the page is loaded
820 // we convert el to the actual element, otherwise we
821 // defer attaching the event until the element is
823 } else if (Y.Lang.isString(el)) {
825 // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el);
828 oEl = Y.DOM.byId(el);
831 oEl = Y.Selector.query(el);
833 switch (oEl.length) {
842 return E._attach(args, config);
850 // Not found = defer adding the event until the element is available
853 ret = this.onAvailable(el, function() {
855 ret.handle = E._attach(args, config);
857 }, E, true, false, compat);
864 // Element should be an html element or node
869 if (Y.Node && el instanceof Y.Node) {
870 el = Y.Node.getDOMNode(el);
873 cewrapper = this._createWrapper(el, type, capture, compat, facade);
875 if (el == Y.config.win && type == "load") {
877 // if the load is complete, fire immediately.
878 // all subscribers, including the current one
880 if (YUI.Env.windowLoaded) {
891 // set context to the Node if not specified
892 // ret = cewrapper.on.apply(cewrapper, trimmedArgs);
893 ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null);
904 * Removes an event listener. Supports the signature the event was bound
905 * with, but the preferred way to remove listeners is using the handle
906 * that is returned when using Y.on
910 * @param {String} type the type of event to remove.
911 * @param {Function} fn the method the event invokes. If fn is
912 * undefined, then all event handlers for the type of event are
914 * @param {String|HTMLElement|Array|NodeList|EventHandle} el An
915 * event handle, an id, an element reference, or a collection
916 * of ids and/or elements to remove the listener from.
917 * @return {boolean} true if the unbind was successful, false otherwise.
920 detach: function(type, fn, el, obj) {
922 var args=Y.Array(arguments, 0, true), compat, i, l, ok,
925 if (args[args.length-1] === COMPAT_ARG) {
930 if (type && type.detach) {
931 return type.detach();
934 // The el argument can be a string
935 if (typeof el == "string") {
937 // el = (compat) ? Y.DOM.byId(el) : Y.all(el);
941 el = Y.Selector.query(el);
949 // return Y.Event.detach.apply(Y.Event, args);
951 // The el argument can be an array of elements or element ids.
958 if (shouldIterate(el)) {
961 for (i=0, l=el.length; i<l; ++i) {
963 ok = ( Y.Event.detach.apply(Y.Event, args) && ok );
970 if (!type || !fn || !fn.call) {
971 return this.purgeElement(el, false, type);
974 id = 'event:' + Y.stamp(el) + type;
978 return ce.detach(fn);
986 * Finds the event in the window object, the caller's arguments, or
987 * in the arguments of another method in the callstack. This is
988 * executed automatically for events registered through the event
989 * manager, so the implementer should not normally need to execute
990 * this function at all.
992 * @param {Event} e the event parameter from the handler
993 * @param {HTMLElement} el the element the listener was attached to
994 * @return {Event} the event
997 getEvent: function(e, el, noFacade) {
998 var ev = e || window.event;
1000 return (noFacade) ? ev :
1001 new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]);
1005 * Generates an unique ID for the element if it does not already
1007 * @method generateId
1008 * @param el the element to create the id for
1009 * @return {string} the resulting id of the element
1012 generateId: function(el) {
1024 * We want to be able to use getElementsByTagName as a collection
1025 * to attach a group of events to. Unfortunately, different
1026 * browsers return different types of collections. This function
1027 * tests to determine if the object is array-like. It will also
1028 * fail if the object is an array, but is empty.
1029 * @method _isValidCollection
1030 * @param o the object to test
1031 * @return {boolean} true if the object is array-like and populated
1032 * @deprecated was not meant to be used directly
1036 _isValidCollection: shouldIterate,
1039 * hook up any deferred listeners
1044 _load: function(e) {
1046 if (!_loadComplete) {
1049 _loadComplete = true;
1051 // Just in case DOMReady did not go off for some reason
1054 Y.fire(EVENT_READY);
1057 // Available elements may not have been detected before the
1058 // window load event fires. Try to find them now so that the
1059 // the user is more likely to get the onAvailable notifications
1060 // before the window load notification
1067 * Polling function that runs before the onload event fires,
1068 * attempting to attach to DOM Nodes as soon as they are
1080 if (Y.UA.ie && !YUI.Env.DOMReady) {
1081 // Hold off if DOMReady has not fired and check current
1082 // readyState to protect against the IE operation aborted
1084 this.startInterval();
1091 // keep trying until after the page is loaded. We need to
1092 // check the page load state prior to trying to bind the
1093 // elements so that we can be certain all elements have been
1094 // tested appropriately
1095 var tryAgain = !_loadComplete, notAvail, executeItem,
1099 tryAgain = (_retryCount > 0);
1105 executeItem = function (el, item) {
1107 var context, ov = item.override;
1111 if (item.override) {
1121 item.fn.call(context, item.obj);
1124 context = item.obj || Y.one(el);
1125 item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []);
1132 for (i=0,len=_avail.length; i<len; ++i) {
1134 if (item && !item.checkReady) {
1136 // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
1137 el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
1140 executeItem(el, item);
1143 notAvail.push(item);
1149 for (i=0,len=_avail.length; i<len; ++i) {
1151 if (item && item.checkReady) {
1153 // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
1154 el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
1157 // The element is available, but not necessarily ready
1158 // @todo should we test parentNode.nextSibling?
1159 if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) {
1160 executeItem(el, item);
1164 notAvail.push(item);
1169 _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1;
1172 // we may need to strip the nulled out items here
1173 this.startInterval();
1175 clearInterval(this._interval);
1176 this._interval = null;
1179 this.locked = false;
1186 * Removes all listeners attached to the given element via addListener.
1187 * Optionally, the node's children can also be purged.
1188 * Optionally, you can specify a specific type of event to remove.
1189 * @method purgeElement
1190 * @param {HTMLElement} el the element to purge
1191 * @param {boolean} recurse recursively purge this element's children
1192 * as well. Use with caution.
1193 * @param {string} type optional type of listener to purge. If
1194 * left out, all listeners will be removed
1197 purgeElement: function(el, recurse, type) {
1198 // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el,
1199 var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el,
1200 lis = this.getListeners(oEl, type), i, len, props;
1202 for (i=0,len=lis.length; i<len ; ++i) {
1205 remove(props.el, props.type, props.fn, props.capture);
1206 delete _wrappers[props.key];
1207 delete _el_events[props.domkey][props.key];
1212 if (recurse && oEl && oEl.childNodes) {
1213 for (i=0,len=oEl.childNodes.length; i<len ; ++i) {
1214 this.purgeElement(oEl.childNodes[i], recurse, type);
1221 * Returns all listeners attached to the given element via addListener.
1222 * Optionally, you can specify a specific type of event to return.
1223 * @method getListeners
1224 * @param el {HTMLElement|string} the element or element id to inspect
1225 * @param type {string} optional type of listener to return. If
1226 * left out, all listeners will be returned
1227 * @return {Y.Custom.Event} the custom event wrapper for the DOM event(s)
1230 getListeners: function(el, type) {
1231 var ek = Y.stamp(el, true), evts = _el_events[ek],
1232 results=[] , key = (type) ? 'event:' + ek + type : null;
1240 results.push(evts[key]);
1243 // get native events as well
1246 results.push(evts[key]);
1250 Y.each(evts, function(v, k) {
1255 return (results.length) ? results : null;
1259 * Removes all listeners registered by pe.event. Called
1260 * automatically during the unload event.
1265 _unload: function(e) {
1266 Y.each(_wrappers, function(v, k) {
1268 remove(v.el, v.type, v.fn, v.capture);
1269 delete _wrappers[k];
1270 delete _el_events[v.domkey][k];
1276 * Adds a DOM event directly without the caching, cleanup, context adj, etc
1279 * @param {HTMLElement} el the element to bind the handler to
1280 * @param {string} type the type of event handler
1281 * @param {function} fn the callback to invoke
1282 * @param {boolen} capture capture or bubble phase
1289 * Basic remove listener
1291 * @method nativeRemove
1292 * @param {HTMLElement} el the element to bind the handler to
1293 * @param {string} type the type of event handler
1294 * @param {function} fn the callback to invoke
1295 * @param {boolen} capture capture or bubble phase
1299 nativeRemove: remove
1307 if (Y.config.injected || YUI.Env.windowLoaded) {
1310 add(window, "load", onLoad);
1313 // Process onAvailable/onContentReady items when when the DOM is ready in IE
1315 Y.on(EVENT_READY, Event._poll, Event, true);
1318 Y.on("unload", onUnload);
1320 Event.Custom = Y.CustomEvent;
1321 Event.Subscriber = Y.Subscriber;
1322 Event.Target = Y.EventTarget;
1323 Event.Handle = Y.EventHandle;
1324 Event.Facade = Y.EventFacade;
1331 * DOM event listener abstraction layer
1333 * @submodule event-base
1337 * Executes the callback as soon as the specified element
1338 * is detected in the DOM.
1340 * @param type {string} 'available'
1341 * @param fn {function} the callback function to execute.
1342 * @param el {string|HTMLElement|collection} the element(s) to attach
1343 * @param context optional argument that specifies what 'this' refers to.
1344 * @param args* 0..n additional arguments to pass on to the callback function.
1345 * These arguments will be added after the event object.
1346 * @return {EventHandle} the detach handle
1349 Y.Env.evt.plugins.available = {
1350 on: function(type, fn, id, o) {
1351 var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : [];
1352 return Y.Event.onAvailable.call(Y.Event, id, fn, o, a);
1357 * Executes the callback as soon as the specified element
1358 * is detected in the DOM with a nextSibling property
1359 * (indicating that the element's children are available)
1360 * @event contentready
1361 * @param type {string} 'contentready'
1362 * @param fn {function} the callback function to execute.
1363 * @param el {string|HTMLElement|collection} the element(s) to attach
1364 * @param context optional argument that specifies what 'this' refers to.
1365 * @param args* 0..n additional arguments to pass on to the callback function.
1366 * These arguments will be added after the event object.
1367 * @return {EventHandle} the detach handle
1370 Y.Env.evt.plugins.contentready = {
1371 on: function(type, fn, id, o) {
1372 var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : [];
1373 return Y.Event.onContentReady.call(Y.Event, id, fn, o, a);
1378 }, '3.0.0' ,{requires:['event-custom-base']});
1379 YUI.add('event-delegate', function(Y) {
1382 * Adds event delegation support to the library.
1385 * @submodule event-delegate
1388 var Event = Y.Event,
1394 mouseenter: "mouseover",
1395 mouseleave: "mouseout"
1398 resolveTextNode = function(n) {
1400 if (n && 3 == n.nodeType) {
1401 return n.parentNode;
1407 delegateHandler = function(delegateKey, e, el) {
1409 var target = resolveTextNode((e.target || e.srcElement)),
1410 tests = delegates[delegateKey],
1418 var getMatch = function(el, selector, container) {
1422 if (!el || el === container) {
1426 returnVal = Y.Selector.test(el, selector) ? el: getMatch(el.parentNode, selector, container);
1434 for (spec in tests) {
1436 if (tests.hasOwnProperty(spec)) {
1438 ename = tests[spec];
1443 if (Y.Selector.test(target, spec, el)) {
1446 else if (Y.Selector.test(target, ((spec.replace(/,/gi, " *,")) + " *"), el)) {
1448 // The target is a descendant of an element matching
1449 // the selector, so crawl up to find the ancestor that
1450 // matches the selector
1452 matched = getMatch(target, spec, el);
1460 ev = new Y.DOMEventFacade(e, el);
1461 ev.container = ev.currentTarget;
1464 ev.currentTarget = Y.Node.get(matched);
1467 contextFn: function() {
1468 return ev.currentTarget;
1486 attach = function (type, key, element) {
1488 var focusMethods = {
1489 focus: Event._attachFocus,
1490 blur: Event._attachBlur
1493 attachFn = focusMethods[type],
1497 delegateHandler(key, (e || window.event), element);
1503 return attachFn(args, { capture: true, facade: false });
1506 return Event._attach(args, { facade: false });
1511 sanitize = Y.cached(function(str) {
1512 return str.replace(/[|,:]/g, '~');
1516 * Sets up event delegation on a container element. The delegated event
1517 * will use a supplied selector to test if the target or one of the
1518 * descendants of the target match it. The supplied callback function
1519 * will only be executed if a match was encountered, and, in fact,
1520 * will be executed for each element that matches if you supply an
1521 * ambiguous selector.
1523 * The event object for the delegated event is supplied to the callback
1524 * function. It is modified slightly in order to support all properties
1525 * that may be needed for event delegation. 'currentTarget' is set to
1526 * the element that matched the delegation specifcation. 'container' is
1527 * set to the element that the listener is bound to (this normally would
1528 * be the 'currentTarget').
1531 * @param type {string} 'delegate'
1532 * @param fn {function} the callback function to execute. This function
1533 * will be provided the event object for the delegated event.
1534 * @param el {string|node} the element that is the delegation container
1535 * @param delegateType {string} the event type to delegate
1536 * @param spec {string} a selector that must match the target of the
1538 * @param context optional argument that specifies what 'this' refers to.
1539 * @param args* 0..n additional arguments to pass on to the callback function.
1540 * These arguments will be added after the event object.
1541 * @return {EventHandle} the detach handle
1543 * @deprecated use Y.delegate
1545 Y.Env.evt.plugins.delegate = {
1547 on: function(type, fn, el, delegateType, spec) {
1550 var args = Y.Array(arguments, 0, true);
1554 args[0] = delegateType;
1556 return Y.delegate.apply(Y, args);
1564 * Sets up event delegation on a container element. The delegated event
1565 * will use a supplied selector to test if the target or one of the
1566 * descendants of the target match it. The supplied callback function
1567 * will only be executed if a match was encountered, and, in fact,
1568 * will be executed for each element that matches if you supply an
1569 * ambiguous selector.
1571 * The event object for the delegated event is supplied to the callback
1572 * function. It is modified slightly in order to support all properties
1573 * that may be needed for event delegation. 'currentTarget' is set to
1574 * the element that matched the delegation specifcation. 'container' is
1575 * set to the element that the listener is bound to (this normally would
1576 * be the 'currentTarget').
1579 * @param type {string} the event type to delegate
1580 * @param fn {function} the callback function to execute. This function
1581 * will be provided the event object for the delegated event.
1582 * @param el {string|node} the element that is the delegation container
1583 * @param spec {string} a selector that must match the target of the
1585 * @param context optional argument that specifies what 'this' refers to.
1586 * @param args* 0..n additional arguments to pass on to the callback function.
1587 * These arguments will be added after the event object.
1588 * @return {EventHandle} the detach handle
1591 Event.delegate = function (type, fn, el, spec) {
1598 var args = Y.Array(arguments, 0, true),
1599 element = el, // HTML element serving as the delegation container
1603 if (Lang.isString(el)) {
1605 // Y.Selector.query returns an array of matches unless specified
1606 // to return just the first match. Since the primary use case for
1607 // event delegation is to use a single event handler on a container,
1608 // Y.delegate doesn't currently support being able to bind a
1609 // single listener to multiple containers.
1611 element = Y.Selector.query(el, null, true);
1613 if (!element) { // Not found, check using onAvailable
1615 availHandle = Event.onAvailable(el, function() {
1617 availHandle.handle = Event.delegate.apply(Event, args);
1619 }, Event, true, false);
1628 element = Y.Node.getDOMNode(element);
1631 var guid = Y.stamp(element),
1633 // The Custom Event for the delegation spec
1634 ename = 'delegate:' + guid + type + sanitize(spec),
1636 // The key to the listener for the event type and container
1637 delegateKey = type + guid,
1639 delegate = delegates[delegateKey],
1652 if (specialTypes[type]) {
1654 if (!Event._fireMouseEnter) {
1658 type = specialTypes[type];
1659 delegate.fn = Event._fireMouseEnter;
1663 // Create the DOM Event wrapper that will fire the Custom Event
1665 domEventHandle = attach(type, delegateKey, element);
1668 // Hook into the _delete method for the Custom Event wrapper of this
1669 // DOM Event in order to clean up the 'delegates' map and unsubscribe
1670 // the associated Custom Event listeners fired by this DOM event
1671 // listener if/when the user calls "purgeElement" OR removes all
1672 // listeners of the Custom Event.
1674 Y.after(function (sub) {
1676 if (domEventHandle.sub == sub) {
1678 // Delete this event from the map of known delegates
1679 delete delegates[delegateKey];
1682 // Unsubscribe all listeners of the Custom Event fired
1683 // by this DOM event.
1688 }, domEventHandle.evt, "_delete");
1690 delegate.handle = domEventHandle;
1692 delegates[delegateKey] = delegate;
1697 listeners = delegate.listeners;
1699 delegate.listeners = listeners ? (listeners + 1) : 1;
1700 delegate[spec] = ename;
1705 // Remove element, delegation spec
1709 // Subscribe to the Custom Event for the delegation spec
1711 ceHandle = Y.on.apply(Y, args);
1714 // Hook into the detach method of the handle in order to clean up the
1715 // 'delegates' map and remove the associated DOM event handler
1716 // responsible for firing this Custom Event if all listener for this
1717 // event have been removed.
1719 Y.after(function () {
1721 delegate.listeners = (delegate.listeners - 1);
1723 if (delegate.listeners === 0) {
1724 delegate.handle.detach();
1727 }, ceHandle, "detach");
1733 Y.delegate = Event.delegate;
1736 }, '3.0.0' ,{requires:['node-base']});
1737 YUI.add('event-mousewheel', function(Y) {
1740 * Adds mousewheel event support
1742 * @submodule event-mousewheel
1744 var DOM_MOUSE_SCROLL = 'DOMMouseScroll',
1745 fixArgs = function(args) {
1746 var a = Y.Array(args, 0, true), target;
1748 a[0] = DOM_MOUSE_SCROLL;
1749 target = Y.config.win;
1751 target = Y.config.doc;
1757 a.splice(2, 0, target);
1764 * Mousewheel event. This listener is automatically attached to the
1765 * correct target, so one should not be supplied. Mouse wheel
1766 * direction and velocity is stored in the 'mouseDelta' field.
1768 * @param type {string} 'mousewheel'
1769 * @param fn {function} the callback to execute
1770 * @param context optional context object
1771 * @param args 0..n additional arguments to provide to the listener.
1772 * @return {EventHandle} the detach handle
1775 Y.Env.evt.plugins.mousewheel = {
1777 return Y.Event._attach(fixArgs(arguments));
1780 detach: function() {
1781 return Y.Event.detach.apply(Y.Event, fixArgs(arguments));
1786 }, '3.0.0' ,{requires:['node-base']});
1787 YUI.add('event-mouseenter', function(Y) {
1790 * Adds support for mouseenter/mouseleave events
1792 * @submodule event-mouseenter
1794 var Event = Y.Event,
1797 plugins = Y.Env.evt.plugins,
1803 on: function(type, fn, el) {
1805 var args = Y.Array(arguments, 0, true),
1810 if (Lang.isString(el)) {
1812 // Need to use Y.all because if el is a string it could be a
1813 // selector that returns a NodeList
1815 element = Y.all(el);
1817 if (element.size() === 0) { // Not found, check using onAvailable
1819 availHandle = Event.onAvailable(el, function() {
1821 availHandle.handle = Y.on.apply(Y, args);
1823 }, Event, true, false);
1832 var sDOMEvent = (type === "mouseenter") ? "mouseover" : "mouseout",
1834 // The name of the custom event
1835 sEventName = type + ":" + Y.stamp(element) + sDOMEvent,
1837 listener = listeners[sEventName],
1846 // Bind an actual DOM event listener that will call the
1850 domEventHandle = Y.on(sDOMEvent, Y.rbind(Event._fireMouseEnter, Y, sEventName), element);
1852 // Hook into the _delete method for the Custom Event wrapper of this
1853 // DOM Event in order to clean up the 'listeners' map and unsubscribe
1854 // the associated Custom Event listeners fired by this DOM event
1855 // listener if/when the user calls "purgeElement" OR removes all
1856 // listeners of the Custom Event.
1858 Y.after(function (sub) {
1860 if (domEventHandle.sub == sub) {
1862 // Delete this event from the map of known mouseenter
1863 // and mouseleave listeners
1864 delete listeners[sEventName];
1867 // Unsubscribe all listeners of the Custom Event fired
1868 // by this DOM event.
1869 Y.detachAll(sEventName);
1873 }, domEventHandle.evt, "_delete");
1877 listener.handle = domEventHandle;
1879 listeners[sEventName] = listener;
1883 nListeners = listener.count;
1885 listener.count = nListeners ? (nListeners + 1) : 1;
1887 args[0] = sEventName;
1889 // Remove the element from the args
1892 // Subscribe to the custom event
1893 ceHandle = Y.on.apply(Y, args);
1895 // Hook into the detach method of the handle in order to clean up the
1896 // 'listeners' map and remove the associated DOM event handler
1897 // responsible for firing this Custom Event if all listener for this
1898 // event have been removed.
1900 Y.after(function () {
1902 listener.count = (listener.count - 1);
1904 if (listener.count === 0) {
1905 listener.handle.detach();
1908 }, ceHandle, "detach");
1918 Event._fireMouseEnter = function (e, eventName) {
1920 var relatedTarget = e.relatedTarget,
1921 currentTarget = e.currentTarget;
1923 if (currentTarget !== relatedTarget &&
1924 !currentTarget.contains(relatedTarget)) {
1926 Y.publish(eventName, {
1927 contextFn: function() {
1928 return currentTarget;
1932 Y.fire(eventName, e);
1940 * Sets up a "mouseenter" listener—a listener that is called the first time
1941 * the user's mouse enters the specified element(s).
1944 * @param type {string} "mouseenter"
1945 * @param fn {function} The method the event invokes.
1946 * @param el {string|node} The element(s) to assign the listener to.
1947 * @param spec {string} Optional. String representing a selector that must
1948 * match the target of the event in order for the listener to be called.
1949 * @return {EventHandle} the detach handle
1952 plugins.mouseenter = eventConfig;
1955 * Sets up a "mouseleave" listener—a listener that is called the first time
1956 * the user's mouse leaves the specified element(s).
1959 * @param type {string} "mouseleave"
1960 * @param fn {function} The method the event invokes.
1961 * @param el {string|node} The element(s) to assign the listener to.
1962 * @param spec {string} Optional. String representing a selector that must
1963 * match the target of the event in order for the listener to be called.
1964 * @return {EventHandle} the detach handle
1967 plugins.mouseleave = eventConfig;
1970 }, '3.0.0' ,{requires:['node-base']});
1971 YUI.add('event-key', function(Y) {
1974 * Functionality to listen for one or more specific key combinations.
1976 * @submodule event-key
1980 * Add a key listener. The listener will only be notified if the
1981 * keystroke detected meets the supplied specification. The
1982 * spec consists of the key event type, followed by a colon,
1983 * followed by zero or more comma separated key codes, followed
1984 * by zero or more modifiers delimited by a plus sign. Ex:
1985 * press:12,65+shift+ctrl
1988 * @param type {string} 'key'
1989 * @param fn {function} the function to execute
1990 * @param id {string|HTMLElement|collection} the element(s) to bind
1991 * @param spec {string} the keyCode and modifier specification
1992 * @param o optional context object
1993 * @param args 0..n additional arguments to provide to the listener.
1994 * @return {Event.Handle} the detach handle
1996 Y.Env.evt.plugins.key = {
1998 on: function(type, fn, id, spec, o) {
1999 var a = Y.Array(arguments, 0, true), parsed, etype, criteria, ename;
2001 parsed = spec && spec.split(':');
2003 if (!spec || spec.indexOf(':') == -1 || !parsed[1]) {
2004 a[0] = 'key' + ((parsed && parsed[0]) || 'press');
2005 return Y.on.apply(Y, a);
2008 // key event type: 'down', 'up', or 'press'
2011 // list of key codes optionally followed by modifiers
2012 criteria = (parsed[1]) ? parsed[1].split(/,|\+/) : null;
2014 // the name of the custom event that will be created for the spec
2015 ename = (Y.Lang.isString(id) ? id : Y.stamp(id)) + spec;
2017 ename = ename.replace(/,/g, '_');
2019 if (!Y.getEvent(ename)) {
2021 // subscribe spec validator to the DOM event
2022 Y.on(type + etype, function(e) {
2025 var passed = false, failed = false, i, crit, critInt;
2027 for (i=0; i<criteria.length; i=i+1) {
2029 critInt = parseInt(crit, 10);
2031 // pass this section if any supplied keyCode
2033 if (Y.Lang.isNumber(critInt)) {
2035 if (e.charCode === critInt) {
2041 // only check modifier if no keyCode was specified
2042 // or the keyCode check was successful. pass only
2043 // if every modifier passes
2044 } else if (passed || !failed) {
2045 passed = (e[crit + 'Key']);
2050 // fire spec custom event if spec if met
2059 // subscribe supplied listener to custom event for spec validator
2060 // remove element and spec.
2064 return Y.on.apply(Y, a);
2069 }, '3.0.0' ,{requires:['node-base']});
2070 YUI.add('event-focus', function(Y) {
2073 * Adds focus and blur event listener support. These events normally
2074 * do not bubble, so this adds support for that so these events
2075 * can be used in event delegation scenarios.
2078 * @submodule event-focus
2084 plugins = Y.Env.evt.plugins,
2086 bUseMutation = (UA.opera || UA.webkit),
2088 focus: (ie ? 'focusin' : (bUseMutation ? 'DOMFocusIn' : 'focus')),
2089 blur: (ie ? 'focusout' : (bUseMutation ? 'DOMFocusOut' : 'blur'))
2092 // Only need to use capture phase for Gecko since it doesn't support
2093 // focusin, focusout, DOMFocusIn, or DOMFocusOut
2094 CAPTURE_CONFIG = { capture: (UA.gecko ? true : false) },
2097 attach = function (args, config) {
2099 var a = Y.Array(args, 0, true);
2100 a[0] = eventNames[a[0]];
2101 return Event._attach(a, config);
2108 return attach(arguments, CAPTURE_CONFIG);
2114 Event._attachFocus = attach;
2115 Event._attachBlur = attach;
2118 * Adds a DOM focus listener. Uses the focusin event in IE,
2119 * DOMFocusIn for Opera and Webkit, and the capture phase for Gecko so that
2120 * the event propagates in a way that enables event delegation.
2124 * @param type {string} 'focus'
2125 * @param fn {function} the callback function to execute
2126 * @param o {string|HTMLElement|collection} the element(s) to bind
2127 * @param context optional context object
2128 * @param args 0..n additional arguments to provide to the listener.
2129 * @return {EventHandle} the detach handle
2131 plugins.focus = eventAdapter;
2134 * Adds a DOM blur listener. Uses the focusout event in IE,
2135 * DOMFocusOut for Opera and Webkit, and the capture phase for Gecko so that
2136 * the event propagates in a way that enables event delegation.
2140 * @param type {string} 'blur'
2141 * @param fn {function} the callback function to execute
2142 * @param o {string|HTMLElement|collection} the element(s) to bind
2143 * @param context optional context object
2144 * @param args 0..n additional arguments to provide to the listener.
2145 * @return {EventHandle} the detach handle
2147 plugins.blur = eventAdapter;
2152 }, '3.0.0' ,{requires:['node-base']});
2153 YUI.add('event-resize', function(Y) {
2156 * Adds a window resize event that has its behavior normalized to fire at the
2157 * end of the resize rather than constantly during the resize.
2159 * @submodule event-resize
2167 CE_NAME = 'window:resize',
2169 handler = function(e) {
2178 timerHandle.cancel();
2181 timerHandle = Y.later(Y.config.windowResizeDelay || 40, Y, function() {
2190 * Firefox fires the window resize event once when the resize action
2191 * finishes, other browsers fire the event periodically during the
2192 * resize. This code uses timeout logic to simulate the Firefox
2193 * behavior in other browsers.
2194 * @event windowresize
2197 Y.Env.evt.plugins.windowresize = {
2199 on: function(type, fn) {
2201 // check for single window listener and add if needed
2202 if (!detachHandle) {
2203 detachHandle = Y.Event._attach(['resize', handler]);
2206 var a = Y.Array(arguments, 0, true);
2209 return Y.on.apply(Y, a);
2216 }, '3.0.0' ,{requires:['node-base']});
2219 YUI.add('event', function(Y){}, '3.0.0' ,{use:['event-base', 'event-delegate', 'event-mousewheel', 'event-mouseenter', 'event-key', 'event-focus', 'event-resize']});