jkj2000 jkj2000 - 1 month ago 11
TypeScript Question

Changing a class variable in a callback function

I'm new to typescript, but I think this is more of a javascript issue than anything else-- specifically, my lack of understanding of how to accomplish something.

I need to set a class-level variable in a callback and am not sure how to go about it. In my typescript class I have a method with a fat arrow function. It calls an object that makes an ajax request with a callback function.

In that callback I would like to set a value on the class. In a nutshell, this is what I've got:

class MyClass extends SomeOtherClass {
protected entity = new Entity();

protected getToolbar() {
toolbarbuttons.push({
title: 'hello',
onClick: () => {
outsideService.makeAjaxCall(
{
url: 'somewhere_in_cyberspace'
},
function (response) {
this.entity.name = response.Name;
}
);
}
});
}
}


That code doesn't work as-is, because in the callback of course 'this' refers to Window and not my class.

Fair enough, and I've tried to do something along the lines of
_that = this
before my onClick handler, I can't get the response values to 'stick' after the handler exits, in the sense that in subsequent methods
this.entity.name
is not what the callback set it to? Something I can do here or have I missed something?

Answer

The 2nd function also needs to be an arrow function:

class MyClass extends SomeOtherClass {
    protected entity = new Entity();

    protected getToolbar() {
        toolbarbuttons.push({
            title: 'hello',
            onClick: () => {
                outsideService.makeAjaxCall({
                    url: 'somewhere_in_cyberspace'
                }, (response) => {
                    this.entity.name = response.Name;
                });
            }
        });
    }
}

This compiles into:

var MyClass = (function (_super) {
    __extends(MyClass, _super);
    function MyClass() {
        _super.apply(this, arguments);
        this.entity = new Entity();
    }
    MyClass.prototype.getToolbar = function () {
        var _this = this;
        toolbarbuttons.push({
            title: 'hello',
            onClick: function () {
                outsideService.makeAjaxCall({
                    url: 'somewhere_in_cyberspace'
                }, function (response) {
                    _this.entity.name = response.Name;
                });
            }
        });
    };
    return MyClass;
}(SomeOtherClass));

As you can see typescript translates the arrow function into a regular anonymous one but it saves a reference var _this = this; which is then used inside the most inner function.

Comments