Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I preserve lexical scope in TypeScript with a callback function

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?

like image 630
Ralph Lavelle Avatar asked Jan 23 '13 03:01

Ralph Lavelle


People also ask

How do you pass a callback function in TypeScript?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.

What is lexical scope in TypeScript?

A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.

Is lexical scope same as closure?

The lexical scope allows a function scope to access statically the variables from the outer scopes. Finally, a closure is a function that captures variables from its lexical scope. In simple words, the closure remembers the variables from the place where it is defined, no matter where it is executed.

What is enclosing lexical scope in JavaScript?

It refers to the specific environment where a variable is accessible and can be used. JavaScript uses the lexical scoping approach which allows for scopes to be nested and therefore an outer scope encloses (hence closure) an inner scope.


3 Answers

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:

public myMethod = (prop1: number): string => {
    return 'asdf';
}

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:

class Test {
   removeRow: (): void;
}

This has now changed to:

class Test {
   removeRow: () => void;
}

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):

class Test {
    removeRow: {
        (): void;
        (param: string): string;
    };
}

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

class Test {

    // Define the method signature here.
    removeRow: () => void;

    constructor (){
        // Implement the method using the fat arrow syntax.
        this.removeRow = () => {
            // Perform your logic to remove the row.
            // Reference `this` as needed.
        }
    }

}

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

class Test {

    // Again, define the method signature here.
    removeRowProxy: () => void;

    constructor (){
        // Assign the method implementation here.
        this.removeRowProxy = () => {
            this.removeRow.apply(this, arguments);
        }
    }

    removeRow(): void {
        // ... removeRow logic here.
    }

}

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:

class Test {

    // Define the method signature here.
    removeRowProxy: () => void;

    constructor (){
        // Use jQuery to bind removeRow to this instance.
        this.removeRowProxy = $.proxy(this.removeRow, this);
    }

    removeRow(): void {
        // ... removeRow logic here.
    }

}

Then you can tidy up your deleteItem method a bit:

// Specify `Function` as the callback type.
// NOTE: You can define a specific signature if needed.
deleteItem(removeRowCallback: Function ): void {
    $.ajax(action, {
        data: { "id": id },
        type: "POST"
    })

    // Pass the callback here.
    // 
    // You don't need the fat arrow syntax here
    // because the callback has already been bound
    // to the correct scope.
    .done(removeRowCallback)

    .fail(() => {
        alert("There was an error!");
    });
}
like image 51
Sly_cardinal Avatar answered Oct 21 '22 15:10

Sly_cardinal


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:

class MyClass {  //no type parameter necessary here

     public myGenericMethod = <T>(someArg:string): QPromise<T> => {

         //implementation here...

     }
}

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:

class Test {

      // Define the method signature AND IMPLEMENTATION here.
      public removeRow: () => void = () => {

        // Perform your logic to remove the row.
        // Reference `this` as needed.

      }

      constructor (){

      }

}

or

Option 5

A little more compact, but gives up explicit return type (the compiler should infer the return type anyway if not explicit):

class Test {

      // Define implementation with implicit signature and correct lexical scope.
      public removeRow = () => {

        // Perform your logic to remove the row.
        // Reference `this` as needed.

      }

      constructor (){

      }

}

like image 42
Zac Morris Avatar answered Oct 21 '22 15:10

Zac Morris


Use .bind() to preserve context within the callback.

Working code example:

window.addEventListener(
  "resize",
  (()=>{this.retrieveDimensionsFromElement();}).bind(this)
)

The code in original question would become something like this:

$.ajax(action, {
    data: { "id": id },
    type: "POST"
})
.done(
  (() => {
    removeRowCallback();
  }).bind(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.

like image 5
Dmitriy Avatar answered Oct 21 '22 15:10

Dmitriy