jquery event:

* event objects have isDefaultPrevented, isPropagationStopped and isImmediatePropagationStopped methods.
* Removed donative and dohandlers from $.trigger
* event.result carries the last returned data from a handler(not undefined).
* $.trigger doesn't keep bubbling if stopPropagation() is called.
* Same event object is used all along for global trigger
* Fixed the bug where target doesn't change when triggering on many elements.
* The data array on $.trigger was accumulating objects as it bubbles.
testrunner: adding more tests
This commit is contained in:
Ariel Flesler 2008-12-31 02:58:13 +00:00
parent 0a846e5be6
commit c0446c70d5
2 changed files with 153 additions and 85 deletions

View file

@ -163,17 +163,32 @@ jQuery.event = {
}
},
trigger: function( e, data, elem, donative, extra) {
trigger: function( event, data, elem, extra) {
// Event object or event type
var type = e.type || e;
var type = event.type || event;
event = typeof event === "object" ?
// jQuery.Event object
event[expando] ? event :
// Object literal
jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string)
jQuery.Event(type);
if ( type.indexOf("!") >= 0 ) {
event.type = type = type.slice(0, -1);
event.exclusive = true;
}
// Handle a global trigger
if ( !elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( this.global[type] )
jQuery.each( jQuery.cache, function(){
if ( this.events && this.events[type] )
jQuery.event.trigger( e, data, this.handle.elem, false );
jQuery.event.trigger( event, data, this.handle.elem );
});
// Handle triggering a single element
@ -186,41 +201,28 @@ jQuery.event = {
// Clone the incoming data, if any
data = jQuery.makeArray(data);
if ( type.indexOf("!") >= 0 ) {
type = type.slice(0, -1);
var exclusive = true;
// AT_TARGET phase (not bubbling)
if( !event.target ){
// Clean up in case it is reused
event.result = undefined;
event.target = elem;
}
e = typeof e === "object" ?
// jQuery.Event object
e[expando] ? e :
// Object literal
jQuery.extend( jQuery.Event(type), e ) :
// Just the event type (string)
jQuery.Event(type);
// Fix for custom events
event.currentTarget = elem;
e.target = e.target || elem;
e.currentTarget = elem;
e.exclusive = exclusive;
data.unshift( event );
data.unshift( e );
var val, ret, fn = jQuery.isFunction( elem[ type ] );
var fn = jQuery.isFunction( elem[ type ] );
// Trigger the event, it is assumed that "handle" is a function
var handle = jQuery.data(elem, "handle");
if ( handle )
val = handle.apply( elem, data );
handle.apply( elem, data );
// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if ( (!fn || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
val = false;
if ( donative !== false && val !== false ) {
var parent = elem.parentNode || elem.ownerDocument;
if ( parent )
jQuery.event.trigger(e, data, parent, donative);
}
event.result = false;
// Extra functions don't get the custom event object
data.shift();
@ -228,14 +230,14 @@ jQuery.event = {
// Handle triggering of extra function
if ( extra && jQuery.isFunction( extra ) ) {
// call the extra function and tack the current return value on the end for possible inspection
ret = extra.apply( elem, val == null ? data : data.concat( val ) );
var ret = extra.apply( elem, event.result == null ? data : data.concat( event.result ) );
// if anything is returned, give it precedence and have it overwrite the previous value
if ( ret !== undefined )
val = ret;
event.result = ret;
}
// Trigger the native events (except for clicks on links)
if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
if ( event.target === elem && fn && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
this.triggered = true;
try {
elem[ type ]();
@ -243,15 +245,22 @@ jQuery.event = {
} catch (e) {}
}
this.triggered = false;
if ( !event.isPropagationStopped() ) {
var parent = elem.parentNode || elem.ownerDocument;
if ( parent )
jQuery.event.trigger(event, data, parent);
}
return val;
// Clean up, in case the event object is reused
event.target = null;
this.triggered = false;
}
},
handle: function(event) {
// returned undefined or false
var val, ret, all, handlers;
var all, handlers;
event = arguments[0] = jQuery.event.fix( event || window.event );
@ -276,23 +285,21 @@ jQuery.event = {
event.handler = handler;
event.data = handler.data;
ret = handler.apply( this, arguments );
if ( val !== false )
val = ret;
var ret = handler.apply(this, arguments);
if( ret !== undefined ){
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if( event._sip )
if( event.isImmediatePropagationStopped() )
break;
}
}
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 toElement view wheelDelta which".split(" "),
@ -403,10 +410,19 @@ jQuery.Event = function( src ){
this[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 = {
// add preventDefault and stopPropagation since
// they will not work on the clone
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if( !e )
return;
@ -417,6 +433,8 @@ jQuery.Event.prototype = {
e.returnValue = false;
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if( !e )
return;
@ -427,9 +445,12 @@ jQuery.Event.prototype = {
e.cancelBubble = true;
},
stopImmediatePropagation:function(){
this._sip = true;
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
@ -488,12 +509,18 @@ jQuery.fn.extend({
trigger: function( type, data, fn ) {
return this.each(function(){
jQuery.event.trigger( type, data, this, true, fn );
jQuery.event.trigger( type, data, this, fn );
});
},
triggerHandler: function( type, data, fn ) {
return this[0] && jQuery.event.trigger( type, data, this[0], false, fn );
if( this[0] ){
var event = jQuery.Event(type);
event.preventDefault();
event.stopPropagation();
jQuery.event.trigger( event, data, this[0], fn );
return event.result;
}
},
toggle: function( fn ) {

View file

@ -269,8 +269,8 @@ test("unbind(event)", function() {
equals( mouseoverCounter, 0, "unbind() with multiple events at once" );
});
test("trigger(event, [data], [fn])", function() {
expect(69);
test("trigger(type, [data], [fn])", function() {
expect(46);
var handler = function(event, a, b, c) {
equals( event.type, "click", "check passed data" );
@ -329,24 +329,6 @@ test("trigger(event, [data], [fn])", function() {
// Trigger only the handlers (no native) and extra fn
// Triggers 8
equals( $elem.triggerHandler("click", [1, "2", "abc"], handler2), false, "Verify handler response" );
var eventObj = jQuery.Event("noNew");
ok( eventObj != window, "Instantiate jQuery.Event without the 'new' keyword" );
equals( eventObj.type, "noNew", "Verify its type" );
// Build fake click event to pass in
eventObj = new jQuery.Event("click");
// Trigger only the handlers (no native), with external event obj
// Triggers 5
equals( $elem.triggerHandler(eventObj, [1, "2", "abc"]), "test", "Verify handler response" );
// Trigger only the handlers (no native) and extra fn, with external event obj
// Triggers 9
eventObj = new jQuery.Event("click");
equals( $elem.triggerHandler(eventObj, [1, "2", "abc"], handler2), false, "Verify handler response" );
var pass = true;
try {
jQuery('#form input:first').hide().trigger('focus');
@ -362,24 +344,83 @@ test("trigger(event, [data], [fn])", function() {
// have the extra handler leave the return value alone
// Triggers 9
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){
test("trigger(eventObject, [data], [fn])", function() {
expect(25);
var $parent = jQuery('<div id="par" />').hide().appendTo('body'),
$child = jQuery('<p id="child">foo</p>').appendTo( $parent );
var event = jQuery.Event("noNew");
ok( event != window, "Instantiate jQuery.Event without the 'new' keyword" );
equals( event.type, "noNew", "Verify its type" );
equals( event.isDefaultPrevented(), false, "Verify isDefaultPrevented" );
equals( event.isPropagationStopped(), false, "Verify isPropagationStopped" );
equals( event.isImmediatePropagationStopped(), false, "Verify isImmediatePropagationStopped" );
event.preventDefault();
equals( event.isDefaultPrevented(), true, "Verify isDefaultPrevented" );
event.stopPropagation();
equals( event.isPropagationStopped(), true, "Verify isPropagationStopped" );
event.isPropagationStopped = function(){ return false };
event.stopImmediatePropagation();
equals( event.isPropagationStopped(), true, "Verify isPropagationStopped" );
equals( event.isImmediatePropagationStopped(), true, "Verify isPropagationStopped" );
$parent.bind('foo',function(e){
// Tries bubbling
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.target.id, 'child', 'Verify event.target when passed passing an event object' );
equals( e.currentTarget.id, 'par', '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 an event object
event = new jQuery.Event("foo");
event.secret = 'boo!';
$child.trigger(event);
// Test with event object and bubbling
jQuery("#simon1").trigger( eventObj );
// test with a literal object
$child.trigger({type:'foo', secret:'boo!'});
// Try passing an object literal
jQuery("#simon1").trigger( {type:'foo', secret:'boo!'} );
$parent.unbind();
$elem.unbind('foo');
function error(){
ok( false, "This assertion shouldn't be reached");
}
$parent.bind('foo', error );
$child.bind('foo',function(e, a, b, c ){
equals( arguments.length, 4, "Check arguments length");
equals( a, 1, "Check first custom argument");
equals( b, 2, "Check second custom argument");
equals( c, 3, "Check third custom argument");
equals( e.isDefaultPrevented(), false, "Verify isDefaultPrevented" );
equals( e.isPropagationStopped(), false, "Verify isPropagationStopped" );
equals( e.isImmediatePropagationStopped(), false, "Verify isImmediatePropagationStopped" );
// Skips both errors
e.stopImmediatePropagation();
return "result";
});
$child.bind('foo', error );
event = new jQuery.Event("foo");
$child.trigger( event, [1,2,3] ).unbind();
equals( event.result, "result", "Check event.result attribute");
// Will error if it bubbles
$child.triggerHandler('foo');
$child.unbind();
$parent.unbind().remove();
});
test("toggle(Function, Function, ...)", function() {