From 4ac6f8d9d322c7e468ed0d58e402abe7bdca354d Mon Sep 17 00:00:00 2001 From: Dave Methvin Date: Sun, 23 Oct 2011 22:25:13 -0400 Subject: [PATCH] Make jQuery().off(event) work for delegated events. Logic to handle detaching by event was in both .off() and jQuery.event.remove; now it's only in .off(). It's a bit of a strange case since the event object (not the jQuery set) specifies the element. --- src/event.js | 22 +++++++++++----------- test/unit/event.js | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/src/event.js b/src/event.js index 42d30e9aa..64cfda530 100644 --- a/src/event.js +++ b/src/event.js @@ -166,13 +166,6 @@ jQuery.event = { return; } - // For removal, types can be an Event object - if ( types && types.type && types.handler ) { - handler = types.handler; - types = types.type; - selector = types.selector; - } - // Once for each type.namespace in types; type may be omitted types = (types || "").replace( rhoverHack, "mouseover$1 mouseout$1" ).split(" "); for ( t = 0; t < types.length; t++ ) { @@ -919,7 +912,8 @@ jQuery.fn.extend({ if ( one === 1 ) { origFn = fn; fn = function( event ) { - jQuery.event.remove( event.currentTarget || this, event ); + // Can use an empty set, since event contains the info + jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn @@ -933,9 +927,15 @@ jQuery.fn.extend({ return this.on.call( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { - if ( types && types.preventDefault ) { - // ( event ) native or jQuery.Event - return this.off( types.type, types.handler, types.selector ); + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + var handleObj = types.handleObj; + jQuery( types.currentTarget ).off( + handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, + handleObj.selector, + handleObj.handler + ); + return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) diff --git a/test/unit/event.js b/test/unit/event.js index 905e6ab99..bb622f577 100644 --- a/test/unit/event.js +++ b/test/unit/event.js @@ -2054,6 +2054,20 @@ test(".delegate()/.undelegate()", function() { jQuery("#body").undelegate("#nothiddendiv div", "click"); }); +test("jQuery.off using dispatched jQuery.Event", function() { + expect(1); + + var markup = jQuery( '

target

' ), + count = 0; + markup + .on( "click.name", "a", function( event ) { + equals( ++count, 1, "event called once before removal" ); + jQuery().off( event ); + }) + .find( "a" ).click().click().end() + .remove(); +}); + test("stopPropagation() stops directly-bound events on delegated target", function() { expect(1); -- 2.39.5