-
-
Save cowboy/a9634a9785e274d64e39 to your computer and use it in GitHub Desktop.
jQuery proxy / partial application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var aps = Array.prototype.slice; | |
jQuery.proxy = function( fn, context ) { | |
var tmp, proxy, partialArgs; | |
// Handle jQuery.proxy( contextObj, nameString ) signature. | |
if ( typeof context === "string" ) { | |
tmp = context; | |
context = fn; | |
fn = context[ tmp ]; | |
} | |
// Get args to be partially applied, only if necessary. | |
if ( arguments.length > 2 ) { | |
partialArgs = aps.call( arguments, 2 ); | |
} | |
// Native bind. | |
if ( jQuery.support.nativeBind ) { | |
if ( partialArgs ) { | |
proxy = fn.bind.apply( fn, [ context ].concat( partialArgs ) ); | |
} else { | |
proxy = fn.bind( context ); | |
} | |
// No native bind. | |
} else if ( partialArgs ) { | |
proxy = function() { | |
var args = arguments.length ? partialArgs.concat( aps.call( arguments ) ) : partialArgs; | |
return fn.apply( context, args ); | |
}; | |
} else { | |
proxy = function() { | |
return arguments.length ? fn.apply( context, args ) : fn.call( context ); | |
}; | |
} | |
// Set the guid of unique handler to the same of original handler, so it can be removed | |
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; | |
// So proxy can be declared as an argument | |
return proxy; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment