42

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?

Ralph Lavelle
  • 5,718
  • 4
  • 36
  • 46
  • 2
    The [`this` keyword](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this) is not the *lexical scope*!!! It's the *context* of the function call. Scope is for variables like `action` or `id`, and they will work in the done callback. – Bergi May 28 '13 at 00:10
  • 19
    Ok. Simmer down old chap. – Ralph Lavelle Sep 26 '13 at 09:36

5 Answers5

61

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!");
    });
}
Community
  • 1
  • 1
Sly_cardinal
  • 12,270
  • 5
  • 49
  • 50
  • Well, thanks for the comprehensive answer! I tried no. 2 and it worked fine. You have a typo though: should only be "{", rather than "{}". – Ralph Lavelle Jan 23 '13 at 04:52
  • 2
    Whoops, fixed that. Autocomplete trying to be too helpful I think :P – Sly_cardinal Jan 23 '13 at 04:59
  • There ya go! Thanks again. – Ralph Lavelle Jan 23 '13 at 05:01
  • 3
    I really wish they'd change this functionality in TypeScript so this is always in the context of the class... maybe have some other way of getting at the context of the caller if necessary. But, then again, I generally don't know what I'm talking about. – Alex Dresko Apr 22 '13 at 20:31
  • 1
    @AlexDresko They can't really change this functionality because it's to do with how JavaScript manages scope on `prototype` functions. e.g. See how the `Greeter.prototype.greet` function ends up in the compiled script here: http://www.typescriptlang.org/Playground/ When the function is defined there is no instance to bind to. That's why we have to work around it in cases like this - sometimes it's a good thing, sometimes a bad thing, but at least it's a known thing :) – Sly_cardinal Apr 23 '13 at 23:41
  • 2
    Well, mostly it's the syntactic hurdles we have to jump through in order to work around the problem. If TS provided some language sugar that made it easier to deal with, I think I'd be happy. :) – Alex Dresko May 01 '13 at 16:07
  • Please note that methods defined using the fat arrow syntax [cannot be accessed using super](http://stackoverflow.com/questions/23218959/typescript-how-to-call-method-defined-with-arrow-function-in-base-class-using-s) which can make them a major pain for OO inheritance. See that question for ways to handle this issue. – claytond Aug 23 '15 at 18:18
  • You may introduce memory leaks by doing `myMethod = (): void => {...}`. The method is defined in the constructor, and the closure includes constructor variables! [Code sample.](http://www.typescriptlang.org/Playground#src=class%20Foo%20%7B%0D%0A%09private%20hello%3A%20string%20%3D%20'Hello'%3B%0D%0A%09constructor()%20%7B%0D%0A%09%09var%20baz%20%3D%20'%20Yikes!'%3B%0D%0A%09%7D%0D%0A%09bar%20%3D%20(who%3A%20string)%3A%20string%20%3D%3E%20%7B%0D%0A%09%09return%20this.hello%20%2B%20who%20%2B%20baz%3B%0D%0A%09%7D%0D%0A%7D%0D%0Aalert(new%20Foo().bar('%20World!'))%3B) – andraaspar Jan 18 '16 at 13:38
  • @andraaspar No it doesn't. Your example raises a typescript compile error – Leo Gerber Feb 01 '17 at 15:18
  • @LeoGerber: That is intentional, to draw attention to the fact that a variable that you (and TypeScript) would not expect to be available there, still is. The variable is then kept in the closure regardless of whether you use it or not. It is not discarded until the method is discarded, hence the value you passed to the constructor cannot be garbage collected, even if the class instance does not use it anymore, for the lifetime of the instance. – andraaspar Feb 01 '17 at 17:15
  • @andraaspar You are absolutely right. This is indeed a problem. It also seems like angular > 2.x has a problem with that syntax. It didn't recognize my ngOninit method anymore. – Leo Gerber Feb 02 '17 at 18:05
36

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 (){

      }

}

Zac Morris
  • 1,846
  • 17
  • 17
  • Brilliant! I didn't realise you could use the fat arrow syntax on the method definition. I thought it would incorrectly share the same function instance amongst all the class instances - but it looks like TypeScript is much smarter than that :) – Sly_cardinal Jan 28 '14 at 01:02
  • I've updated my answer to point to yours now that you've posted a better (and more correct) solution. I have added a note about Option 5 as well - we can specify the parameters and return type without any repetition :) – Sly_cardinal Jan 28 '14 at 01:14
  • Thanks for the tip on 5! I had tried but couldn't figure out the right syntax to get the return type in there. I hate leaving things implicit. – Zac Morris Jan 28 '14 at 15:09
  • Please note that methods defined using the fat arrow syntax [cannot be accessed using super](http://stackoverflow.com/questions/23218959/typescript-how-to-call-method-defined-with-arrow-function-in-base-class-using-s) which can make them a major pain for OO inheritance. See that question for ways to handle this issue. – claytond Aug 23 '15 at 18:17
  • Thanks for this. Just a small note: It doesn't *have* to be above the constructor (it is a variable alright, but in my case it started as a method that was given to another object, which calls some other protected methods - so was important for me to have it below the constructor) – Izhaki Sep 21 '16 at 23:33
5

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.

Dmitriy
  • 525
  • 5
  • 11
2

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/

class Test {

    private testString: string = "Fancy this!";

    // Define the method signature here.
    removeRowLambdaCallback(outerThis: Test): {(): void} {
        alert("Defining callback for consumption");
        return function(){
            alert(outerThis.testString); // lexically scoped class instance
            alert(this); // dynamically scoped context caller
            // Put logic here for removing rows. Can refer to class
            // instance as well as "this" passed by a library such as JQuery or D3.
        }
    }
    // This approach looks nicer, but is more dangerous
    // because someone might use this method itself, rather
    // than the return value, as a callback.
     anotherRemoveRowLambdaCallback(): {(): void} {
        var outerThis = this;
        alert("Defining another callback for consumption");
        return function(){
            alert(outerThis.testString); // lexically scoped class instance
            alert(this); // dynamically scoped context caller
            // Put logic here for removing rows. Can refer to class
            // instance as well as "this" passed by a library such as JQuery or D3.
        }
    }
}

var t = new Test();
var callback1 = t.removeRowLambdaCallback(t);
var callback2 = t.anotherRemoveRowLambdaCallback();

callback1();
callback2();
Community
  • 1
  • 1
Eric
  • 663
  • 7
  • 18
  • 1
    Something about having to pass an instance method the instance itself makes me want to take a shower... The prior two answers are cleaner. The compiler creates `_this` automatically for lexical scoping, and `this` still refers to dynamic context. Not quite sure of the advantage gained through your solution. – gravidThoughts Mar 23 '15 at 16:43
0

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"

type MyCallback = () => string;

class HelloWorld {

    // The callback
    public callback: MyCallback = () => {
        return 'world';
    }

    // The caller
    public caller(callback: MyCallback) {
        alert('Hello ' + callback());
    }
}

let hello = new HelloWorld();
hello.caller(hello.callback);

This gets transpiled into:

var HelloWorld = (function () {
    function HelloWorld() {
        // The callback
        this.callback = function () {
            return 'world';
        };
    }
    // The caller
    HelloWorld.prototype.caller = function (callback) {
        alert('Hello ' + callback());
    };
    return HelloWorld;
}());
var hello = new HelloWorld();
hello.caller(hello.callback);

Hope someone finds it just a little useful. :)

DarkNeuron
  • 7,981
  • 2
  • 43
  • 48