Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created January 3, 2011 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboy/a9634a9785e274d64e39 to your computer and use it in GitHub Desktop.
Save cowboy/a9634a9785e274d64e39 to your computer and use it in GitHub Desktop.
jQuery proxy / partial application
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