event.js revision 537e74c4e869b8efba925d0e37c0a5636203a23b
550N/A * DOM event listener abstraction layer 919N/A// Unlike most of the library, this code has to be executed as soon as it is 919N/A// introduced into the page -- and it should only be executed one time 550N/A// regardless of the number of instances that use it. 550N/A // Internet Explorer: use the readyState of a defered script. 550N/A // This isolates what appears to be a safe moment to manipulate 550N/A // the DOM prior to when the document's readyState suggests 550N/A // it is safe to do so. 550N/A // throws an error if doc is not ready 550N/A // FireFox, Opera, Safari 3+: These browsers provide a event for this 550N/A ///////////////////////////////////////////////////////////// YUI.
add(
'event',
function(Y) {
* DOM event listener abstraction layer * Executes the supplied callback when the DOM is first usable. This * will execute immediately if called after the DOMReady event has * fired. @todo the DOMContentReady event does not fire when the * script is dynamically injected into the page. This means the * DOMReady custom event will never fire in FireFox or Opera when the * library is injected. It _will_ fire in Safari, and the IE * implementation would allow for us to fire it if the defered script * is not available. We want this to behave the same in all browsers. * Is there a way to identify when the script has been injected * instead of included inline? Is there a way to know whether the * window onload event has fired without having had a listener attached * <p>The callback is a Event.Custom, so the signature is:</p> * <p>type <string>, args <array>, customobject <object></p> * <p>For DOMReady events, there are no fire argments, so the * <p>"DOMReady", [], obj</p> * @param {function} fn what to execute when the element is found. * @optional context optional execution context * @optional args 0..n arguments to send to the listener * Use domready event instead. @see domready * @deprecated use 'domready' instead // console.log('DOMReady already fired', 'info', 'event'); // console.log('setting up before listener', 'info', 'event'); // console.log('env: ' + YUI.Env.windowLoaded, 'info', 'event'); * Custom event engine, DOM event listener abstraction layer, synthetic DOM * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event * @TODO constants? LEFTBUTTON, MIDDLEBUTTON, RIGHTBUTTON, keys // "button" : 1, // we supply // "bubbles" : 1, // needed? // "cancelable" : 1, // needed? // "charCode" : 1, // we supply // "currentTarget" : 1, // we supply detail : 1, // not fully implemented // "height" : 1, // needed? // "initEvent" : 1, // need the init events? // "layerX" : 1, // needed? // "layerY" : 1, // needed? // "modifiers" : 1, // needed? // "offsetX" : 1, // needed? // "offsetY" : 1, // needed? // "preventDefault" : 1, // we supply // "reason" : 1, // IE proprietary // "returnValue" : 1, // needed? // "srcUrn" : 1, // IE proprietary // "srcFilter" : 1, IE proprietary // "stopPropagation" : 1, // we supply // "timeStamp" : 1, // needed? // "which" : 1, // we supply // "width" : 1, // needed? * webkit key remapping required for Safari < 3.1 25:
9 // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text // provide a single event with browser abstractions resolved // include all properties for both browers? // include only DOM2 spec properties? // provide browser-specific facade? ////////////////////////////////////////////////////// * The X location of the event on the page (including scroll) * The Y location of the event on the page (including scroll) ////////////////////////////////////////////////////// * The keyCode for key events. Uses charCode if keyCode is not available * The charCode for key events. Same as keyCode ////////////////////////////////////////////////////// * The button that was pushed. * The button that was pushed. Same as button. ////////////////////////////////////////////////////// * Node reference for the targeted element * Node reference for the element that the listener was attached to. if (e.
type ==
"mouseout") {
}
else if (e.
type ==
"mouseover") {
* Node reference to the relatedTarget ////////////////////////////////////////////////////// * Stops the propagation to the next bubble target * @method stopPropagation * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * @method stopImmediatePropagation * Prevents the event's default behavior * Stops the event propagation and prevents the default * @param immediate {boolean} if true additional listeners * on the current target will not be executed * DOM event listener abstraction layer * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. // if (o instanceof Y.Node) { return ( o &&
// o is something typeof o !==
"string" &&
// o is not a string // o.length && // o is indexed !o.
tagName &&
// o is not an HTML element !o.
alert &&
// o is not a window (o.
item ||
typeof o[
0] !==
"undefined") );
* True after the onload event has fired * @property _loadComplete * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * The poll interval in milliseconds * @property POLL_INTERVAL * These errors are suppressed, the method returns false, and this property * document readystate poll handle * True when the document is initially usable * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * @param {string||string[]} id the id of the element, or an array * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @deprecated Use Y.on("available") for (i=
0; i<a.
length; i=i+
1) {
// We want the first test to be immediate, but async return new Y.
EventHandle();
// @TODO by id needs a defered handle * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} p_obj an optional object to be passed back as * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * @deprecated Use Y.on("contentready") * Appends an event handler * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * @param {Object} obj An arbitrary object that will be * passed as a parameter to the handler * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {Boolean} True if the action was successful or defered, * false if one or more of the elements * could not have the listener attached, * or if the operation throws an exception. // for later removeListener calls // window load happens once // throw new TypeError(type + " attach call failed, callback undefined"); // The el argument can be an array of elements or element ids. // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // @TODO switch to using DOM directly here // oEl = (compat) ? Y.DOM.byId(el) : Y.all(el); // Not found = defer adding the event until the element is available // Element should be an html element or an array if we get here. // the custom event key is the uid for the element + type // allow a node reference to Y.on to work with load time addEventListener check // (Node currently only has the addEventListener interface and that may be // if the load is complete, fire immediately. // all subscribers, including the current one // switched from obj to trimmedArgs[2] to deal with appened compat param // context = trimmedArgs[2] || ((compat) ? el : Y.get(el)); // set the context as the second arg to subscribe // remove the 'obj' param // set context to the Node if not specified * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to remove * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @return {boolean} true if the unbind was successful, false * otherwise. // The el argument can be a string if (
typeof el ==
"string") {
// el = (compat) ? Y.DOM.byId(el) : Y.all(el); // The el argument can be an array of elements or element ids. * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * Generates an unique ID for the element if it does not already * @param el the element to create the id for * @return {string} the resulting id of the element * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * hook up any deferred listeners // Just in case DOMReady did not go off for some reason // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // el = (item.compat) ? Y.DOM.byId(item.id) : Y.get(item.id); // el = (item.compat) ? Y.DOM.byId(item.id) : Y.get(item.id); // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? // we may need to strip the nulled out items here * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed // var oEl = (Y.Lang.isString(el)) ? Y.get(el) : el, * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {Y.Custom.Event} the custom event wrapper for the DOM event(s) * Removes all listeners registered by pe.event. Called * automatically during the unload event. * Adds a DOM event directly without the caching, cleanup, context adj, etc * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * Executes the callback as soon as the specified element * is detected in the DOM. * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string|HTMLElement|collection} the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available) * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string|HTMLElement|collection} the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle // Opera implents capture phase events per spec rather than // the more useful way it is implemented in other browsers: // The event doesn't fire on a target unless there is a // listener on an element in the target's ancestry. If a // capture phase listener is added only to the element that // will be the target of the event, the listener won't fire. // To get around this, we register a NOOP listener on the * Adds a DOM focus listener. Uses the focusin event in IE, * and the capture phase otherwise so that * the event propagates in a way that enables event delegation. * Note: if you are registering this event on the intended target * rather than an ancestor, the element must be in the DOM in * order for it to work in Opera. * @param type {string} 'focus' * @param fn {function} the callback function to execute * @param o {string|HTMLElement|collection} the element(s) to bind * @param context optional context object * @param args 0..n additional arguments to provide to the listener. * @return {EventHandle} the detach handle * Adds a DOM blur listener. Uses the focusout event in IE, * and the capture phase otherwise so that * the event propagates in a way that enables event delegation. * Note: if you are registering this event on the intended target * rather than an ancestor, the element must be in the DOM * at the time of registration in order for it to work in Opera. * @param type {string} 'focus' * @param fn {function} the callback function to execute * @param o {string|HTMLElement|collection} the element(s) to bind * @param context optional context object * @param args 0..n additional arguments to provide to the listener. * @return {EventHandle} the detach handle * Add a key listener. The listener will only be notified if the * keystroke detected meets the supplied specification. The * spec consists of the key event type, followed by a colon, * followed by zero or more comma separated key codes, followed * by zero or more modifiers delimited by a plus sign. Ex: * @param type {string} 'key' * @param fn {function} the function to execute * @param id {string|HTMLElement|collection} the element(s) to bind * @param spec {string} the keyCode and modifier specification * @param o optional context object * @param args 0..n additional arguments to provide to the listener. * @return {Event.Handle} the detach handle // key event type: 'down', 'up', or 'press' // list of key codes optionally followed by modifiers // the name of the custom event that will be created for the spec // subscribe spec validator to the DOM event // pass this section if any supplied keyCode // only check modifier if no keyCode was specified // or the keyCode check was successful. pass only // if every modifier passes // fire spec custom event if spec if met // subscribe supplied listener to custom event for spec validator // remove element and spec. // @TODO this approach makes it so we can't delegate custom // event types like focus and blur. There isn't currently // a way to make these events emit the native event payload, // so trying to fix this might mean that the implementation // needs to be prepared for both payloads. * Sets up event delegation on a container element. The delegated event * will use a supplied selector to test if the target or one of the * descendants of the target match it. The supplied callback function * will only be executed if a match was encountered, and, in fact, * will be executed for each element that matches if you supply an * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the delegation specifcation. 'container' is * set to the element that the listener is bound to (this normally would * be the 'currentTarget'). * @param type {string} 'delegate' * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param delegateType {string} the event type to delegate * @param spec {string} a selector that must match the target of the * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle // identifier to target the container // the custom event for the delegation spec // the key to the listener for the event type and container // remove element, delegation spec and context object from the args // subscribe to the custom event for the delegation spec * Firefox fires the window resize event once when the resize action * finishes, other browsers fire the event periodically during the * resize. This code uses timeout logic to simulate the Firefox * behavior in other browsers. // check for single window listener and add if needed var sDOMEvent = (
type ===
"mouseenter") ?
"mouseover" :
"mouseout",
// Set up the listener on the container // Remove the element (and the spec--if defined) from the args // Subscribe to the custom event for the delegation spec * Sets up a "mouseenter" listener—a listener that is called the first time * the user's mouse enters the specified element(s). By passing a CSS selector * as the fourth argument, can also be used to delegate a "mouseenter" * @param type {string} "mouseenter" * @param fn {function} The method the event invokes. * @param el {string|node} The element(s) to assign the listener to. * @param spec {string} Optional. String representing a selector that must * match the target of the event in order for the listener to be called. * @return {EventHandle} the detach handle * Sets up a "mouseleave" listener—a listener that is called the first time * the user's mouse leaves the specified element(s). By passing a CSS selector * as the fourth argument, can also be used to delegate a "mouseleave" * @param type {string} "mouseleave" * @param fn {function} The method the event invokes. * @param el {string|node} The element(s) to assign the listener to. * @param spec {string} Optional. String representing a selector that must * match the target of the event in order for the listener to be called. * @return {EventHandle} the detach handle },
'@VERSION@' ,{
requires:[
'event-custom']});