【问题标题】:Changing a class variable in a callback function在回调函数中更改类变量
【发布时间】:2017-03-16 10:48:18
【问题描述】:

我是 typescript 的新手,但我认为这更像是一个 javascript 问题而不是其他任何事情——具体来说,我对如何完成某事缺乏了解。

我需要在回调中设置一个类级别的变量,但不知道如何去做。在我的打字稿类中,我有一个带有粗箭头函数的方法。它调用一个使用回调函数发出 ajax 请求的对象。

在那个回调中,我想为类设置一个值。简而言之,这就是我所拥有的:

 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;
                }
            );
         }     
    });
  }
}

该代码不能按原样工作,因为在回调中,“this”当然是指 Window 而不是我的类。

很公平,我已经尝试在我的 onClick 处理程序之前按照_that = this 的方式做一些事情,但在处理程序退出后,我无法将响应值设置为“stick”,从某种意义上说,在后续方法中this.entity.name 不是回调设置的吗?我可以在这里做些什么还是我错过了什么?

【问题讨论】:

  • 您是否尝试过将回调设为箭头函数?目前,this.entity.name = response.Name 位于 function 声明中的位,而不是类似于 (response) => { ... 的位置。这可能是问题
  • 我会试试的,谢谢。

标签: javascript typescript callback


【解决方案1】:

第二个函数也需要是箭头函数:

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;
                });
            }
        });
    }
}

编译成:

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

如您所见,typescript 将箭头函数转换为常规匿名函数,但它保存了一个引用 var _this = this;,然后在最内部的函数中使用该引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-28
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    相关资源
    最近更新 更多