I have a TypeScript class, with a function that I intend to use as a callback:
removeRow(_this:MyClass): void {
...
// 'this' is now the window object
// I must use '_this' to get the class itself
...
}
I pass it in to another function
this.deleteRow(this.removeRow);
which in turn calls a jQuery Ajax method, which if successful, invokes the callback like this:
deleteItem(removeRowCallback: (_this:MyClass) => void ): void {
$.ajax(action, {
data: { "id": id },
type: "POST"
})
.done(() => {
removeRowCallback(this);
})
.fail(() => {
alert("There was an error!");
});
}
The only way I can preserve the 'this' reference to my class is to pass it on to the callback, as demonstrated above. It works, but it's pants code. If I don't wire up the 'this' like this (sorry), then any reference to this in the callback method has reverted to the Window object. Because I'm using arrow functions all the way, I expected that the 'this' would be the class itself, as it is elsewhere in my class.
Anyone know how to pass callbacks around in TypeScript, preserving lexical scope?
Building upon sly and Zac's answers with types: A complete hello world example. I hope this is welcome, seeing as this is the top result in Google, when searching for "typescript javascript callbacks"
This gets transpiled into:
Hope someone finds it just a little useful. :)
UPDATE: See Sly's updated answer. It incorporates an improved version of the options below.
ANOTHER UPDATE: Generics
Sometimes you want to specify a generic type in a function signature without having to specify it on the the whole class. It took me a few tries to figure out the syntax, so I thought it might be worth sharing:
Option 4
Here are a couple more syntaxes to add to Sly_cardinal's answer. These examples keep the function declaration and implementation in the same place:
}
or
Option 5
A little more compact, but gives up explicit return type (the compiler should infer the return type anyway if not explicit):
}
Use .bind() to preserve context within the callback.
Working code example:
The code in original question would become something like this:
It will set the context (this) inside the callback function to whatever was passed as an argument to bind function, in this case the original this object.
Edit 2014-01-28:
New readers, make sure you check out Zac's answer below.
He has a much neater solution that will let you define and instantiate a scoped function in the class definition using the fat arrow syntax.
The only thing I will add is that, in regard to option 5 in Zac's answer, it's possible to specify the method signature and return type without any repetition using this syntax:
Edit 2013-05-28:
The syntax for defining a function property type has changed (since TypeScript version 0.8).
Previously you would define a function type like this:
This has now changed to:
I have updated my answer below to include this new change.
As a further aside: If you need to define multiple function signatures for the same function name (e.g. runtime function overloading) then you can use the object map notation (this is used extensively in the jQuery descriptor file):
You need to define the signature for
removeRow()
as a property on your class but assign the implementation in the constructor.There are a few different ways you can do this.
Option 1
If you want to keep your constructor minimal then you can just keep the
removeRow
method in the class definition and just assign a proxy function in the constructor:Option 2
Option 3
And finally, if you're using a library like underscore or jQuery then you can just use their utility method to create the proxy:
Then you can tidy up your
deleteItem
method a bit:This is sort of a cross post from another answer (Is there an alias for 'this' in TypeScript?). I re-applied the concept using the examples from above. I like it better than the options above because it explictly supports "this" scoping to both the class instance as well as the dynamic context entity that calls the method.
There are two versions below. I like the first one because the compiler assists in using it correctly (you won't as easily try to misuse the callback lambda itself as the callback, because of the explicitly typed parameter).
Test it out: http://www.typescriptlang.org/Playground/