Skip to content

Commit 31432e0

Browse files
committed
Add .delegate() and .undelegate(). An alternative to using .live() which goes from a single root and filters by the specified selectors. Should be used like do: .delegate(td, hover, someFn);. Fixes #6005.
1 parent cb65daa commit 31432e0

File tree

2 files changed

+433
-38
lines changed

2 files changed

+433
-38
lines changed

src/event.js

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -866,6 +866,20 @@ jQuery.fn.extend({
866866

867867
return this;
868868
},
869+
870+
delegate: function( selector, types, data, fn ) {
871+
return this.live( types, data, fn, selector );
872+
},
873+
874+
undelegate: function( selector, types, fn ) {
875+
if ( arguments.length === 0 ) {
876+
return this.unbind( "live" );
877+
878+
} else {
879+
return this.die( types, null, fn, selector );
880+
}
881+
},
882+
869883
trigger: function( type, data ) {
870884
return this.each(function() {
871885
jQuery.event.trigger( type, data, this );
@@ -910,8 +924,10 @@ jQuery.fn.extend({
910924
});
911925

912926
jQuery.each(["live", "die"], function( i, name ) {
913-
jQuery.fn[ name ] = function( types, data, fn ) {
914-
var type, i = 0;
927+
jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
928+
var type, i = 0,
929+
selector = origSelector || this.selector,
930+
context = origSelector ? this : jQuery( this.context );
915931

916932
if ( jQuery.isFunction( data ) ) {
917933
fn = data;
@@ -928,13 +944,13 @@ jQuery.each(["live", "die"], function( i, name ) {
928944

929945
if ( name === "live" ) {
930946
// bind live handler
931-
jQuery( this.context ).bind( liveConvert( type, this.selector ), {
932-
data: data, selector: this.selector, live: type
947+
context.bind( liveConvert( type, selector ), {
948+
data: data, selector: selector, live: type
933949
}, fn );
934950

935951
} else {
936952
// unbind live handler
937-
jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null );
953+
context.unbind( liveConvert( type, selector ), fn ? { guid: fn.guid + selector + type } : null );
938954
}
939955
}
940956

@@ -1002,7 +1018,7 @@ function liveHandler( event ) {
10021018
}
10031019

10041020
function liveConvert( type, selector ) {
1005-
return "live." + (type ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&");
1021+
return "live." + (type && type !== "*" ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&");
10061022
}
10071023

10081024
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +

0 commit comments

Comments
 (0)