Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Added in jQuery.proxy(obj, name), like the method described in Secret…

…s of the JavaScript Ninja and in Dojo's Hitch, and added in some unit tests.
  • Loading branch information...
commit 1d2b1a57dae0b73b3d99197f73f4edb623b5574a 1 parent a5dbca4
John Resig authored December 31, 2009
25  src/core.js
@@ -618,17 +618,28 @@ jQuery.extend({
618 618
 	guid: 1,
619 619
 
620 620
 	proxy: function( fn, proxy, thisObject ) {
621  
-		if ( arguments.length === 2 && proxy && !jQuery.isFunction( proxy ) ) {
622  
-			thisObject = proxy;
623  
-			proxy = undefined;
  621
+		if ( arguments.length === 2 ) {
  622
+			if ( typeof proxy === "string" ) {
  623
+				thisObject = fn;
  624
+				fn = thisObject[ proxy ];
  625
+				proxy = undefined;
  626
+
  627
+			} else if ( proxy && !jQuery.isFunction( proxy ) ) {
  628
+				thisObject = proxy;
  629
+				proxy = undefined;
  630
+			}
624 631
 		}
625 632
 
626  
-		proxy = proxy || function() {
627  
-			return fn.apply( thisObject || this, arguments );
628  
-		};
  633
+		if ( !proxy && fn ) {
  634
+			proxy = function() {
  635
+				return fn.apply( thisObject || this, arguments );
  636
+			};
  637
+		}
629 638
 
630 639
 		// Set the guid of unique handler to the same of original handler, so it can be removed
631  
-		proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
  640
+		if ( fn ) {
  641
+			proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
  642
+		}
632 643
 
633 644
 		// So proxy can be declared as an argument
634 645
 		return proxy;
19  test/unit/core.js
@@ -839,3 +839,22 @@ test("jQuery.isEmptyObject", function(){
839 839
 	// What about this ?
840 840
 	// equals(true, jQuery.isEmptyObject(null), "isEmptyObject on null" );
841 841
 });
  842
+
  843
+test("jQuery.proxy", function(){
  844
+	expect(4);
  845
+
  846
+	var test = function(){ equals( this, thisObject, "Make sure that scope is set properly." ); };
  847
+	var thisObject = { foo: "bar", method: test };
  848
+
  849
+	// Make sure normal works
  850
+	test.call( thisObject );
  851
+
  852
+	// Basic scoping
  853
+	jQuery.proxy( test, thisObject )();
  854
+
  855
+	// Make sure it doesn't freak out
  856
+	equals( jQuery.proxy( null, thisObject ), undefined, "Make sure no function was returned." );
  857
+
  858
+	// Use the string shortcut
  859
+	jQuery.proxy( thisObject, "method" )();
  860
+});

0 notes on commit 1d2b1a5

Please sign in to comment.
Something went wrong with that request. Please try again.