🌐 AI搜索 & 代理 主页
Skip to content

Commit 1d2b1a5

Browse files
committed
Added in jQuery.proxy(obj, name), like the method described in Secrets of the JavaScript Ninja and in Dojo's Hitch, and added in some unit tests.
1 parent a5dbca4 commit 1d2b1a5

File tree

2 files changed

+37
-7
lines changed

2 files changed

+37
-7
lines changed

src/core.js

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -618,17 +618,28 @@ jQuery.extend({
618618
guid: 1,
619619

620620
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+
}
624631
}
625632

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+
}
629638

630639
// 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+
}
632643

633644
// So proxy can be declared as an argument
634645
return proxy;

test/unit/core.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -839,3 +839,22 @@ test("jQuery.isEmptyObject", function(){
839839
// What about this ?
840840
// equals(true, jQuery.isEmptyObject(null), "isEmptyObject on null" );
841841
});
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 commit comments

Comments
 (0)