Reputation: 10230
Was just going through the source code of jQuery $.proxy , and came across the following lines of code , see below:
if (typeof context === "string") {
tmp = fn[context];
context = fn;
fn = tmp;
}
The entire function code can be seen HERE, what i want to know is , what is the above code provision for , I.E. when does the above code come into play ? can anybody explain ? I totally understand what the code is doing but , what i would like to know is a real code situation in which such a piece of code would be useful.
EDIT::
The entire function code can be seen below:
function (fn, context) {
var args, proxy, tmp;
if (typeof context === "string") {
tmp = fn[context];
context = fn;
fn = tmp;
}
// 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;
}
// Simulated bind
args = slice.call(arguments, 2);
proxy = function () {
return fn.apply(context || this, args.concat(slice.call(arguments)));
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
}
Thank you.
Upvotes: 3
Views: 54
Reputation: 193271
You seem to understand the purpose of $.proxy but wondering when it can be useful to be able to pass a string as a "context"? Well, the way I see it is mostly a matter of preference really, because both signatures can be used interchangeably.
Here is the typical usage of the $.proxy (or Funtion.prototype.bind):
var user = {
username: 'Thomas Mann',
getUsername: function() {
alert(this.username);
}
};
$('button').click($.proxy(user.getUsername, user));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Check</button>
Nothing special. However, jQuery proxy implementation allows you to swap base object and context, so above example could also be rewritten as follows:
var user = {
username: 'Thomas Mann',
getUsername: function() {
alert(this.username);
}
};
$('button').click($.proxy(user, 'getUsername'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Check</button>
So in this case you pass context first and then method name to call on the context object.
Note however, that classical Function.prototype.bind follows the first notation. I recommend to do the same for consistency. I also haven't seen anyone using it the second way so better to avoid this not very clear syntax.
Upvotes: 2