07-event.js | |
---|---|
jQuery Annotated Source. | |
Events | var rnamespaces = /\.(.*)$/,
rformElems = /^(?:textarea|input|select)$/i,
rperiod = /\./g,
rspaces = / /g,
rescape = /[^\w\s.|`]/g,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
}; |
A number of helper functions used for managing events. Many of the ideas behind this code originated from Dean Edwards' addEvent library. | jQuery.event = { |
Bind an event to an element Original by Dean Edwards | add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
} else if ( !handler ) { |
Fixes bug #7229. Fix recommended by jdalton | return;
}
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
} |
Make sure that the function being executed has a unique ID | if ( !handler.guid ) {
handler.guid = jQuery.guid++;
} |
Init the element's event structure | var elemData = jQuery._data( elem ); |
If no elemData is found then we must be trying to bind to one of the banned noData elements | if ( !elemData ) {
return;
}
var events = elemData.events,
eventHandle = elemData.handle;
if ( !events ) {
elemData.events = events = {};
}
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) { |
Discard the second event of a jQuery.event.trigger() and when an event is called after a page has unloaded | return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
} |
Add elem as a property of the handle function This is to prevent a memory leak with non-native events in IE. | eventHandle.elem = elem; |
Handle multiple events separated by a space jQuery(...).bind("mouseover mouseout", fn); | types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data }; |
Namespaced event handlers | if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
if ( !handleObj.guid ) {
handleObj.guid = handler.guid;
} |
Get the current list of functions bound to this event | var handlers = events[ type ],
special = jQuery.event.special[ type ] || {}; |
Init the event handler queue | if ( !handlers ) {
handlers = events[ type ] = []; |
Check for a special event handler Only use addEventListener/attachEvent if the special events handler returns false | if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { |
Bind the global event handler to the element | if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
} |
Add the function to the element's handler list | handlers.push( handleObj ); |
Keep track of which events have been used, for event optimization | jQuery.event.global[ type ] = true;
} |
Nullify elem to prevent memory leaks in IE | elem = null;
},
global: {}, |
Detach an event or set of events from an element | remove: function( elem, types, handler, pos ) { |
don't do events on text and comment nodes | if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
}
var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
events = elemData && elemData.events;
if ( !elemData || !events ) {
return;
} |
types is actually an event object here | if ( types && types.type ) {
handler = types.handler;
types = types.type;
} |
Unbind all events for the element | if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
types = types || "";
for ( type in events ) {
jQuery.event.remove( elem, type + types );
}
return;
} |
Handle multiple events separated by a space jQuery(...).unbind("mouseover mouseout", fn); | types = types.split(" ");
while ( (type = types[ i++ ]) ) {
origType = type;
handleObj = null;
all = type.indexOf(".") < 0;
namespaces = [];
if ( !all ) { |
Namespaced event handlers | namespaces = type.split(".");
type = namespaces.shift();
namespace = new RegExp("(^|\\.)" +
jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
}
eventType = events[ type ];
if ( !eventType ) {
continue;
}
if ( !handler ) {
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( all || namespace.test( handleObj.namespace ) ) {
jQuery.event.remove( elem, origType, handleObj.handler, j );
eventType.splice( j--, 1 );
}
}
continue;
}
special = jQuery.event.special[ type ] || {};
for ( j = pos || 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( handler.guid === handleObj.guid ) { |
remove the given handler for the given type | if ( all || namespace.test( handleObj.namespace ) ) {
if ( pos == null ) {
eventType.splice( j--, 1 );
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
if ( pos != null ) {
break;
}
}
} |
remove generic event handler if no more handlers exist | if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
ret = null;
delete events[ type ];
}
} |
Remove the expando if it's no longer used | if ( jQuery.isEmptyObject( events ) ) {
var handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
delete elemData.events;
delete elemData.handle;
if ( jQuery.isEmptyObject( elemData ) ) {
jQuery.removeData( elem, undefined, true );
}
}
},
|
Events that are safe to short-circuit if no handlers are attached. Native DOM events should not be added, they may have inline handlers. | customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) { |
Event object or event type | var type = event.type || event,
namespaces = [],
exclusive;
if ( type.indexOf("!") >= 0 ) { |
Exclusive events trigger only for the exact event (no namespaces) | type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf(".") >= 0 ) { |
Namespaced trigger; create a regexp to match event type in handle() | namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { |
No jQuery handlers for this event type, and it can't have inline handlers | return;
} |
Caller can pass in an Event, Object, or just an event type string | event = typeof event === "object" ? |
jQuery.Event object | event[ jQuery.expando ] ? event : |
Object literal | new jQuery.Event( type, event ) : |
Just the event type (string) | new jQuery.Event( type );
event.type = type;
event.exclusive = exclusive;
event.namespace = namespaces.join(".");
event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
|
triggerHandler() and global events don't bubble or run the default action | if ( onlyHandlers || !elem ) {
event.preventDefault();
event.stopPropagation();
} |
Handle a global trigger | if ( !elem ) { |
TODO: Stop taunting the data cache; remove global events and always attach to document | jQuery.each( jQuery.cache, function() { |
internalKey variable is just used to make it easier to find and potentially change this stuff later; currently it just points to jQuery.expando | var internalKey = jQuery.expando,
internalCache = this[ internalKey ];
if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
jQuery.event.trigger( event, data, internalCache.handle.elem );
}
});
return;
} |
Don't do events on text and comment nodes | if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
} |
Clean up the event in case it is being reused | event.result = undefined;
event.target = elem; |
Clone any incoming data and prepend the event, creating the handler arg list | data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
var cur = elem, |
IE doesn't like method names with a colon (#3533, #8272) | ontype = type.indexOf(":") < 0 ? "on" + type : ""; |
Fire event on the current element, then bubble up the DOM tree | do {
var handle = jQuery._data( cur, "handle" );
event.currentTarget = cur;
if ( handle ) {
handle.apply( cur, data );
} |
Trigger an inline bound script | if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) {
event.result = false;
event.preventDefault();
} |
Bubble up to document, then to window | cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window;
} while ( cur && !event.isPropagationStopped() ); |
If nobody prevented the default action, do it now | if ( !event.isDefaultPrevented() ) {
var old,
special = jQuery.event.special[ type ] || {};
if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { |
Call a native DOM method on the target with the same name name as the event. Can't use an .isFunction)() check here because IE6/7 fails that test. IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. | try {
if ( ontype && elem[ type ] ) { |
Don't re-trigger an onFOO event when we call its FOO() method | old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
jQuery.event.triggered = type;
elem[ type ]();
}
} catch ( ieError ) {}
if ( old ) {
elem[ ontype ] = old;
}
jQuery.event.triggered = undefined;
}
}
return event.result;
},
handle: function( event ) {
event = jQuery.event.fix( event || window.event ); |
Snapshot the handlers list since a called handler may add/remove events. | var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0),
run_all = !event.exclusive && !event.namespace,
args = Array.prototype.slice.call( arguments, 0 ); |
Use the fix-ed Event rather than the (read-only) native event | args[0] = event;
event.currentTarget = this;
for ( var j = 0, l = handlers.length; j < l; j++ ) {
var handleObj = handlers[ j ]; |
Triggered event must 1) be non-exclusive and have no namespace, or 2) have namespace(s) a subset or equal to those in the bound event. | if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { |
Pass in a reference to the handler function itself So that we can later remove it | event.handler = handleObj.handler;
event.data = handleObj.data;
event.handleObj = handleObj;
var ret = handleObj.handler.apply( this, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return event.result;
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
} |
store a copy of the original event object and "clone" to set read-only properties | var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ) {
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
} |
Fix target property, if necessary | if ( !event.target ) { |
Fixes #1925 where srcElement might not be defined either | event.target = event.srcElement || document;
} |
check if target is a textnode (safari) | if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
} |
Add relatedTarget, if necessary | if ( !event.relatedTarget && event.fromElement ) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
} |
Calculate pageX/Y if missing and clientX/Y available | if ( event.pageX == null && event.clientX != null ) {
var eventDocument = event.target.ownerDocument || document,
doc = eventDocument.documentElement,
body = eventDocument.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
} |
Add which for key events | if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
} |
Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) | if ( !event.metaKey && event.ctrlKey ) {
event.metaKey = event.ctrlKey;
} |
Add which for click: 1 === left; 2 === middle; 3 === right Note: button is not normalized, so don't use it | if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
return event;
}, |
Deprecated, use jQuery.guid instead | guid: 1E8, |
Deprecated, use jQuery.proxy instead | proxy: jQuery.proxy,
special: {
ready: { |
Make sure the ready event is setup | setup: jQuery.bindReady,
teardown: jQuery.noop
},
live: {
add: function( handleObj ) {
jQuery.event.add( this,
liveConvert( handleObj.origType, handleObj.selector ),
jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
},
remove: function( handleObj ) {
jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
}
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) { |
We only want to do this special case on windows | if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) { |
Allow instantiation without the 'new' keyword | if ( !this.preventDefault ) {
return new jQuery.Event( src, props );
} |
Event object | if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type; |
Events bubbling up the document may have been marked as prevented by a handler lower down the tree; reflect the correct value. | this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; |
Event type | } else {
this.type = src;
} |
Put explicitly provided properties onto the event object | if ( props ) {
jQuery.extend( this, props );
} |
timeStamp is buggy for some events on Firefox(#3843) So we won't rely on the native value | this.timeStamp = jQuery.now(); |
Mark it as fixed | this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
} |
jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html | jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
} |
if preventDefault exists run it on the original event | if ( e.preventDefault ) {
e.preventDefault(); |
otherwise set the returnValue property of the original event to false (IE) | } else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
} |
if stopPropagation exists run it on the original event | if ( e.stopPropagation ) {
e.stopPropagation();
} |
otherwise set the cancelBubble property of the original event to true (IE) | e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
}; |
Checks if an event happened on an element within another element Used in jQuery.event.special.mouseenter and mouseleave handlers | var withinElement = function( event ) { |
Check if mouse(over|out) are still within the same parent element | var related = event.relatedTarget,
inside = false,
eventType = event.type;
event.type = event.data;
if ( related !== this ) {
if ( related ) {
inside = jQuery.contains( this, related );
}
if ( !inside ) {
jQuery.event.handle.apply( this, arguments );
event.type = eventType;
}
}
}, |
In case of event delegation, we only need to rename the event.type, liveHandler will take care of the rest. | delegate = function( event ) {
event.type = event.data;
jQuery.event.handle.apply( this, arguments );
}; |
Create mouseenter and mouseleave events | jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
setup: function( data ) {
jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
},
teardown: function( data ) {
jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
}
};
}); |
submit delegation | if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
if ( !jQuery.nodeName( this, "form" ) ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
trigger( "submit", this, arguments );
}
});
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
trigger( "submit", this, arguments );
}
});
} else {
return false;
}
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialSubmit" );
}
};
} |
change delegation, happens here so we have bind. | if ( !jQuery.support.changeBubbles ) {
var changeFilters,
getVal = function( elem ) {
var type = elem.type, val = elem.value;
if ( type === "radio" || type === "checkbox" ) {
val = elem.checked;
} else if ( type === "select-multiple" ) {
val = elem.selectedIndex > -1 ?
jQuery.map( elem.options, function( elem ) {
return elem.selected;
}).join("-") :
"";
} else if ( jQuery.nodeName( elem, "select" ) ) {
val = elem.selectedIndex;
}
return val;
},
testChange = function testChange( e ) {
var elem = e.target, data, val;
if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
return;
}
data = jQuery._data( elem, "_change_data" );
val = getVal(elem); |
the current data will be also retrieved by beforeactivate | if ( e.type !== "focusout" || elem.type !== "radio" ) {
jQuery._data( elem, "_change_data", val );
}
if ( data === undefined || val === data ) {
return;
}
if ( data != null || val ) {
e.type = "change";
e.liveFired = undefined;
jQuery.event.trigger( e, arguments[1], elem );
}
};
jQuery.event.special.change = {
filters: {
focusout: testChange,
beforedeactivate: testChange,
click: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) {
testChange.call( this, e );
}
}, |
Change has to be called before submit Keydown will be called before keypress, which is used in submit-event delegation | keydown: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) ||
(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
type === "select-multiple" ) {
testChange.call( this, e );
}
}, |
Beforeactivate happens also before the previous element is blurred with this event you can't trigger a change event, but you can store information | beforeactivate: function( e ) {
var elem = e.target;
jQuery._data( elem, "_change_data", getVal(elem) );
}
},
setup: function( data, namespaces ) {
if ( this.type === "file" ) {
return false;
}
for ( var type in changeFilters ) {
jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
}
return rformElems.test( this.nodeName );
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialChange" );
return rformElems.test( this.nodeName );
}
};
changeFilters = jQuery.event.special.change.filters; |
Handle when the input is .focus()'d | changeFilters.focus = changeFilters.beforeactivate;
}
function trigger( type, elem, args ) { |
Piggyback on a donor event to simulate a different one. Fake originalEvent to avoid donor's stopPropagation, but if the simulated event prevents default then we do the same on the donor. Don't pass args or remember liveFired; they apply to the donor event. | var event = jQuery.extend( {}, args[ 0 ] );
event.type = type;
event.originalEvent = {};
event.liveFired = undefined;
jQuery.event.handle.call( elem, event );
if ( event.isDefaultPrevented() ) {
args[ 0 ].preventDefault();
}
} |
Create "bubbling" focus and blur events | if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { |
Attach a single capturing handler while someone wants focusin/focusout | var attaches = 0;
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
function handler( donor ) { |
Donor event is always a native one; fix it and switch its type. Let focusin/out handler cancel the donor focus/blur event. | var e = jQuery.event.fix( donor );
e.type = fix;
e.originalEvent = {};
jQuery.event.trigger( e, null, e.target );
if ( e.isDefaultPrevented() ) {
donor.preventDefault();
}
}
});
}
jQuery.each(["bind", "one"], function( i, name ) {
jQuery.fn[ name ] = function( type, data, fn ) {
var handler; |
Handle object literals | if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( arguments.length === 2 || data === false ) {
fn = data;
data = undefined;
}
if ( name === "one" ) {
handler = function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
};
handler.guid = fn.guid || jQuery.guid++;
} else {
handler = fn;
}
if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn );
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
return this;
};
});
jQuery.fn.extend({
unbind: function( type, fn ) { |
Handle object literals | if ( typeof type === "object" && !type.preventDefault ) {
for ( var key in type ) {
this.unbind(key, type[key]);
}
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.remove( this[i], type, fn );
}
}
return this;
},
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
},
undelegate: function( selector, types, fn ) {
if ( arguments.length === 0 ) {
return this.unbind( "live" );
} else {
return this.die( types, null, fn, selector );
}
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) { |
Save reference to arguments for access in closure | var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) { |
Figure out which function to execute | var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); |
Make sure that clicks stop | event.preventDefault(); |
and execute the function | return args[ lastToggle ].apply( this, arguments ) || false;
}; |
link all the functions, so any of them can unbind this click handler | toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
var liveMap = {
focus: "focusin",
blur: "focusout",
mouseenter: "mouseover",
mouseleave: "mouseout"
};
jQuery.each(["live", "die"], function( i, name ) {
jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
return this;
}
if ( name === "die" && !types &&
origSelector && origSelector.charAt(0) === "." ) {
context.unbind( origSelector );
return this;
}
if ( data === false || jQuery.isFunction( data ) ) {
fn = data || returnFalse;
data = undefined;
}
types = (types || "").split(" ");
while ( (type = types[ i++ ]) != null ) {
match = rnamespaces.exec( type );
namespaces = "";
if ( match ) {
namespaces = match[0];
type = type.replace( rnamespaces, "" );
}
if ( type === "hover" ) {
types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
continue;
}
preType = type;
if ( liveMap[ type ] ) {
types.push( liveMap[ type ] + namespaces );
type = type + namespaces;
} else {
type = (liveMap[ type ] || type) + namespaces;
}
if ( name === "live" ) { |
bind live handler | for ( var j = 0, l = context.length; j < l; j++ ) {
jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
}
} else { |
unbind live handler | context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
return this;
};
});
function liveHandler( event ) {
var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
elems = [],
selectors = [],
events = jQuery._data( this, "events" ); |
Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) | if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
return;
}
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.liveFired = this;
var live = events.live.slice(0);
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
selectors.push( handleObj.selector );
} else {
live.splice( j--, 1 );
}
}
match = jQuery( event.target ).closest( selectors, event.currentTarget );
for ( i = 0, l = match.length; i < l; i++ ) {
close = match[i];
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) {
elem = close.elem;
related = null; |
Those two events require additional checking | if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
event.type = handleObj.preType;
related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; |
Make sure not to accidentally match a child element with the same selector | if ( related && jQuery.contains( elem, related ) ) {
related = elem;
}
}
if ( !related || related !== elem ) {
elems.push({ elem: elem, handleObj: handleObj, level: close.level });
}
}
}
}
for ( i = 0, l = elems.length; i < l; i++ ) {
match = elems[i];
if ( maxLevel && match.level > maxLevel ) {
break;
}
event.currentTarget = match.elem;
event.data = match.handleObj.data;
event.handleObj = match.handleObj;
ret = match.handleObj.origHandler.apply( match.elem, arguments );
if ( ret === false || event.isPropagationStopped() ) {
maxLevel = match.level;
if ( ret === false ) {
stop = false;
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return stop;
}
function liveConvert( type, selector ) {
return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&");
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error").split(" "), function( i, name ) { |
Handle event binding | jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
});
|