diff options
author | Gianni Chiappetta <gianni@runlevel6.org> | 2010-12-14 21:53:04 -0500 |
---|---|---|
committer | Gianni Chiappetta <gianni@runlevel6.org> | 2010-12-14 21:53:04 -0500 |
commit | 9f8cd6c499844451468257140e71f611abb3a040 (patch) | |
tree | 0390a7c2268c29b0e1a28c4d6fe80b8e5e2eb808 /src/core.js | |
parent | c9c9057c4d4097767ca181bdb4bb27d6fd2d8fbd (diff) | |
download | jquery-9f8cd6c499844451468257140e71f611abb3a040.tar.gz jquery-9f8cd6c499844451468257140e71f611abb3a040.zip |
Fixing $.proxy to work like (and use) Function.prototype.bind (ticket #7783)
http://bugs.jquery.com/ticket/7783
Diffstat (limited to 'src/core.js')
-rw-r--r-- | src/core.js | 49 |
1 files changed, 30 insertions, 19 deletions
diff --git a/src/core.js b/src/core.js index 346e52d70..74ec4ea03 100644 --- a/src/core.js +++ b/src/core.js @@ -740,31 +740,42 @@ jQuery.extend({ // A global GUID counter for objects guid: 1, - proxy: function( fn, proxy, thisObject ) { - if ( arguments.length === 2 ) { - if ( typeof proxy === "string" ) { - thisObject = fn; - fn = thisObject[ proxy ]; - proxy = undefined; - - } else if ( proxy && !jQuery.isFunction( proxy ) ) { - thisObject = proxy; - proxy = undefined; - } + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var args, proxy; + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( ! jQuery.isFunction( fn ) ) { + return undefined; } - if ( !proxy && fn ) { - proxy = function() { - return fn.apply( thisObject || this, arguments ); - }; + if ( jQuery.isFunction( Function.prototype.bind ) ) { + // Native bind + args = slice.call( arguments, 1 ); + proxy = Function.prototype.bind.apply( fn, args ); + } else { + // Simulated bind + args = slice.call( arguments, 2 ); + if ( args.length ) { + proxy = function() { + return arguments.length ? + fn.apply( context, args.concat( slice.call( arguments ) ) ) : + fn.apply( context, args ); + }; + } else { + proxy = function() { + return arguments.length ? + fn.apply( context, arguments ) : + fn.call( context ); + }; + } } // Set the guid of unique handler to the same of original handler, so it can be removed - if ( fn ) { - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - } + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - // So proxy can be declared as an argument return proxy; }, |