This project is read-only.

How do you model callbacks?

Topics: General
Oct 3, 2012 at 7:01 PM
Edited Oct 3, 2012 at 7:30 PM

E.g. I want a function in my class to acception a callback function as a parameter. 

Can you specify what the signature of this function should be ?

function Foo( parameter1 : string, foocallback : function( a:string, b:number ) ) {
   foocallback( "test",123 );

Update: I found I could express it as 

function Foo(parameter1: string, foocallback: (a:string, b:number)=>void)

But wat I really would like to do, is to define this callback signature as a type (like delegate in c#)?
So that if the signature of the callback changes, I don't have to revisit all functions using the callback... only refactor the delegate definition.

Oct 3, 2012 at 8:04 PM

You can use an interface for this:

interface FooDelegate {
    (a: string, b: number): void;

Now you can use the type FooDelegate for foocallback and you'll be set.

Oct 3, 2012 at 8:17 PM

Great! That works...