Reputation: 741
I often use a construct like this:
var $this, url, callback; //some private vars
loadCallback = function($that, url, callback) {
return function(responseText, textStatus, req) {
...
};
})($this, url, callback)
However that is not quite comfortable. Is there some alternative?
I already took a look at jQuery.proxy, but that functions seems to fix the "this" variable so loadCallback can not get called applying another "this" context.
Upvotes: 1
Views: 83
Reputation: 60414
In modern browsers use bind
. Implement your own simple version like this:
function bind(fn, _this) {
var _args = Array.prototype.slice.call(arguments, 2);
return function() {
return fn.apply(_this, _args.concat(Array.prototype.slice.call(arguments)));
}
}
Usage:
var loadCallback = bind(function(url, responseText, textStatus, req) {
console.log(url, responseText)
}, this, url);
A more complete polyfill can be found on MDN.
Upvotes: 2