jquery event: Closes #3662. Adds a jQuery.Event class. Makes trigger and fix simpler. Adds currentTarget attribute to event objects. Event object isn't passed as part of data.

This commit is contained in:
Ariel Flesler 2008-12-25 21:44:54 +00:00
parent 8cd50a398d
commit 4ca4ce52f7
2 changed files with 107 additions and 82 deletions

View file

@ -163,51 +163,49 @@ jQuery.event = {
} }
}, },
trigger: function(type, data, elem, donative, extra, dohandlers) { trigger: function( e, data, elem, donative, extra, dohandlers) {
// Clone the incoming data, if any // Event object or event type
data = jQuery.makeArray(data); var type = e.type || e;
if ( type.indexOf("!") >= 0 ) {
type = type.slice(0, -1);
var exclusive = true;
}
// Handle a global trigger // Handle a global trigger
if ( !elem ) { if ( !elem ) {
// Only trigger if we've ever bound an event for it // Only trigger if we've ever bound an event for it
if ( this.global[type] ) if ( this.global[type] )
jQuery.each( jQuery.cache, function(){ jQuery.each( jQuery.cache, function(){
if ( this.events && this.events[type] ) if ( this.events && this.events[type] )
jQuery.event.trigger( type, data, this.handle.elem, false ); jQuery.event.trigger( e, data, this.handle.elem, false );
}); });
// Handle triggering a single element // Handle triggering a single element
} else { } else {
// don't do events on text and comment nodes // don't do events on text and comment nodes
if ( elem.nodeType == 3 || elem.nodeType == 8 ) if ( elem.nodeType == 3 || elem.nodeType == 8 )
return undefined; return undefined;
var val, ret, fn = jQuery.isFunction( elem[ type ] || null ), // Clone the incoming data, if any
// Check to see if we need to provide a fake event, or not data = jQuery.makeArray(data);
event = !data[0] || !data[0].preventDefault;
if ( type.indexOf("!") >= 0 ) {
// Pass along a fake event type = type.slice(0, -1);
if ( event ) { var exclusive = true;
data.unshift({
type: type,
target: elem,
preventDefault: function(){},
stopPropagation: function(){},
stopImmediatePropagation:stopImmediatePropagation,
timeStamp: now()
});
data[0][expando] = true; // no need to fix fake event
} }
e = typeof e === "object" ?
// jQuery.Event object
e[expando] ? e :
// Object literal
jQuery.extend( new jQuery.Event(type), e ) :
// Just the event type (string)
new jQuery.Event(type);
e.target = e.target || elem;
e.currentTarget = elem;
e.exclusive = exclusive;
data.unshift( e );
// Enforce the right trigger type var val, ret, fn = jQuery.isFunction( elem[ type ] );
data[0].type = type;
if ( exclusive )
data[0].exclusive = true;
if ( dohandlers !== false ) { if ( dohandlers !== false ) {
// Trigger the event, it is assumed that "handle" is a function // Trigger the event, it is assumed that "handle" is a function
@ -223,12 +221,11 @@ jQuery.event = {
if ( donative !== false && val !== false ) { if ( donative !== false && val !== false ) {
var parent = elem.parentNode || elem.ownerDocument; var parent = elem.parentNode || elem.ownerDocument;
if ( parent ) if ( parent )
jQuery.event.trigger(type, data, parent, donative); jQuery.event.trigger(e, data, parent, donative);
} }
// Extra functions don't get the custom event object // Extra functions don't get the custom event object
if ( event ) data.shift();
data.shift();
// Handle triggering of extra function // Handle triggering of extra function
if ( extra && jQuery.isFunction( extra ) ) { if ( extra && jQuery.isFunction( extra ) ) {
@ -300,7 +297,7 @@ jQuery.event = {
return val; return val;
}, },
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" "), props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function(event) { fix: function(event) {
if ( event[expando] ) if ( event[expando] )
@ -309,38 +306,13 @@ jQuery.event = {
// store a copy of the original event object // store a copy of the original event object
// and "clone" to set read-only properties // and "clone" to set read-only properties
var originalEvent = event; var originalEvent = event;
event = { originalEvent: originalEvent }; event = new jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ){ for ( var i = this.props.length, prop; i; ){
prop = this.props[ --i ]; prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ]; event[ prop ] = originalEvent[ prop ];
} }
// Mark it as fixed
event[expando] = true;
// add preventDefault and stopPropagation since
// they will not work on the clone
event.preventDefault = function() {
// if preventDefault exists run it on the original event
if (originalEvent.preventDefault)
originalEvent.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
originalEvent.returnValue = false;
};
event.stopPropagation = function() {
// if stopPropagation exists run it on the original event
if (originalEvent.stopPropagation)
originalEvent.stopPropagation();
// otherwise set the cancelBubble property of the original event to true (IE)
originalEvent.cancelBubble = true;
};
event.stopImmediatePropagation = stopImmediatePropagation;
// Fix timeStamp
event.timeStamp = event.timeStamp || now();
// Fix target property, if necessary // Fix target property, if necessary
if ( !event.target ) if ( !event.target )
event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
@ -413,11 +385,50 @@ jQuery.event = {
} }
}; };
function stopImmediatePropagation(){ jQuery.Event = function( src ){
this._sip = 1; // Event object
this.stopPropagation(); if( src && src.type ){
} this.originalEvent = src;
this.type = src.type;
// Fix timeStamp
this.timeStamp = src.timeStamp || now();
// Event type
}else
this.type = src;
// Mark it as fixed
this[expando] = true;
};
jQuery.Event.prototype = {
// add preventDefault and stopPropagation since
// they will not work on the clone
preventDefault: function() {
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)
e.returnValue = false;
},
stopPropagation: function() {
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._sip = true;
this.stopPropagation();
}
};
// Checks if an event happened on an element within another element // Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers // Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function(event) { var withinElement = function(event) {

View file

@ -301,54 +301,50 @@ test("trigger(event, [data], [fn])", function() {
equals( c, "abc", "check passed data" ); equals( c, "abc", "check passed data" );
equals( v, "test", "check current value" ); equals( v, "test", "check current value" );
}; };
var $elem = jQuery("#firstp");
// Simulate a "native" click // Simulate a "native" click
jQuery("#firstp")[0].click = function(){ $elem[0].click = function(){
ok( true, "Native call was triggered" ); ok( true, "Native call was triggered" );
}; };
// Triggers handlrs and native // Triggers handlrs and native
// Trigger 5 // Trigger 5
jQuery("#firstp").bind("click", handler).trigger("click", [1, "2", "abc"]); $elem.bind("click", handler).trigger("click", [1, "2", "abc"]);
// Triggers handlers, native, and extra fn // Triggers handlers, native, and extra fn
// Triggers 9 // Triggers 9
jQuery("#firstp").trigger("click", [1, "2", "abc"], handler4); $elem.trigger("click", [1, "2", "abc"], handler4);
// Simulate a "native" click // Simulate a "native" click
jQuery("#firstp")[0].click = function(){ $elem[0].click = function(){
ok( false, "Native call was triggered" ); ok( false, "Native call was triggered" );
}; };
// Triggers handlers, native, and extra fn
// Triggers 7
jQuery("#firstp").trigger("click", [1, "2", "abc"], handler2);
// Trigger only the handlers (no native) // Trigger only the handlers (no native)
// Triggers 5 // Triggers 5
equals( jQuery("#firstp").triggerHandler("click", [1, "2", "abc"]), "test", "Verify handler response" ); equals( $elem.triggerHandler("click", [1, "2", "abc"]), "test", "Verify handler response" );
// Trigger only the handlers (no native) and extra fn // Trigger only the handlers (no native) and extra fn
// Triggers 8 // Triggers 8
equals( jQuery("#firstp").triggerHandler("click", [1, "2", "abc"], handler2), false, "Verify handler response" ); equals( $elem.triggerHandler("click", [1, "2", "abc"], handler2), false, "Verify handler response" );
// Build fake click event to pass in // Build fake click event to pass in
var eventObj = jQuery.event.fix({ type: "foo", target: document.body }); var eventObj = new jQuery.Event("click");
// Trigger only the handlers (no native), with external event obj // Trigger only the handlers (no native), with external event obj
// Triggers 5 // Triggers 5
equals( jQuery("#firstp").triggerHandler("click", [eventObj, 1, "2", "abc"]), "test", "Verify handler response" ); equals( $elem.triggerHandler(eventObj, [1, "2", "abc"]), "test", "Verify handler response" );
// Trigger only the handlers (no native) and extra fn, with external event obj // Trigger only the handlers (no native) and extra fn, with external event obj
// Triggers 9 // Triggers 9
eventObj = jQuery.event.fix({ type: "foo", target: document.body }); eventObj = new jQuery.Event("click");
equals( jQuery("#firstp").triggerHandler("click", [eventObj, 1, "2", "abc"], handler), "test", "Verify handler response" ); equals( $elem.triggerHandler(eventObj, [1, "2", "abc"], handler2), false, "Verify handler response" );
var pass = true; var pass = true;
try { try {
jQuery('#form input:first') jQuery('#form input:first').hide().trigger('focus');
.hide()
.trigger('focus');
} catch(e) { } catch(e) {
pass = false; pass = false;
} }
@ -356,11 +352,29 @@ test("trigger(event, [data], [fn])", function() {
// have the extra handler override the return // have the extra handler override the return
// Triggers 9 // Triggers 9
equals( jQuery("#firstp").triggerHandler("click", [1, "2", "abc"], handler3), "newVal", "Verify triggerHandler return is overwritten by extra function" ); equals( $elem.triggerHandler("click", [1, "2", "abc"], handler3), "newVal", "Verify triggerHandler return is overwritten by extra function" );
// have the extra handler leave the return value alone // have the extra handler leave the return value alone
// Triggers 9 // Triggers 9
equals( jQuery("#firstp").triggerHandler("click", [1, "2", "abc"], handler4), "test", "Verify triggerHandler return is not overwritten by extra function" ); equals( $elem.triggerHandler("click", [1, "2", "abc"], handler4), "test", "Verify triggerHandler return is not overwritten by extra function" );
$elem.unbind('click').bind('foo',function(e){
equals( e.type, 'foo', 'Verify event type when passed passing an event object' );
equals( e.target.id, 'simon1', 'Verify event.target when passed passing an event object' );
equals( e.currentTarget.id, 'firstp', 'Verify event.target when passed passing an event object' );
equals( e.secret, 'boo!', 'Verify event object\'s custom attribute when passed passing an event object' );
});
eventObj = new jQuery.Event('foo');
eventObj.secret = 'boo!';
// Test with event object and bubbling
jQuery("#simon1").trigger( eventObj );
// Try passing an object literal
jQuery("#simon1").trigger( {type:'foo', secret:'boo!'} );
$elem.unbind('foo');
}); });
test("toggle(Function, Function, ...)", function() { test("toggle(Function, Function, ...)", function() {