@poke's answer is the right idea, but there are a couple issues:
function thisAsThat (callback) {
return function () {
return callback.apply(null, [this].concat(arguments));
}
}
First, arguments
is not a true array, so calling concat()
as shown above will result in a nested array:
[0] = this
[1] = [ [0] = param1, [1] = param2, ... ]
To fix this, use slice() to convert arguments
to a true array:
return callback.apply(null, [this].concat(Array.prototype.slice.call(arguments)));
Result:
[0] = this
[1] = param1
[2] = param2
...
Second, passing null
for the first parameter to apply() didn't work for me; I had to pass class Foo's this
explicitly. Here's a complete example:
class Foo {
public setClickHandler(checkbox: JQuery): void {
checkbox.click(this.captureThis(this.onCheckboxClick));
}
protected onCheckboxClick(checkbox: HTMLInputElement, event: Event) {
// 'this' refers to class Foo
}
protected captureThis(callback) {
var self = this;
return function () {
return callback.apply(self, [this].concat(Array.prototype.slice.call(arguments)));
}
}
}
With this approach, the onCheckboxClick()
callback has access to both the class this
and the checkbox element (as the first parameter) that would have been this
in a typical click
event callback. The downside to using captureThis()
is that you lose TypeScript's type safety for the callback, so Typescript can't stop you from messing up the callback function signature.