【问题标题】:callback retains class level variable value typescript回调保留类级别变量值打字稿
【发布时间】:2020-06-30 11:17:55
【问题描述】:

我有一个带有一些变量的类和一个从外部库调用函数的函数,这个函数需要这样的回调:

class UserGestures {

    private gestureManager : HammerManager;
    private gestureDetected : string;

    constructor() {

        this.gestureManager = new Hammer.Manager(document.body);
        this.detectOnElement.addEventListener('touchend', this.resetGestures);
        this.gestureDetected = "OUTER";

        this.startDetection();
    }

    private startDetection() {

        this.gestureManager.on('pinch rotate pan', (e : HammerInput) => {

            console.log(this.gestureDetected);

            if(this.gestureDetected === "OUTER") {
                console.log("checking for new gesture");
                this.gestureDetected = "INNER";
            }
        });
    }

    private resetGestures() {
        console.log("reset");
        this.gestureDetected = "OUTER";
        console.log(this.gestureDetected);
    }
}

我遇到的问题是我第一次运行此代码时。来自this.gestureManager.on('pinch rotate pan', (e : HammerInput) => {} 的事件触发我按以下顺序看到以下console.logs:

OUTER
checking for new gesture
INNER

现在当resetGestures 函数触发时,我看到以下内容:

reset
OUTER

这一切都符合预期。但现在问题来了...
this.gestureManager.on('pinch rotate pan', (e : HammerInput) => {} 再次触发时,我看到以下 console.logs:

INNER

而不是预期的:

OUTER
checking for new gesture
INNER

为什么会这样?我认为正在发生的是回调在本地存储 this.gestureDetected 的值,而不是在定义它的类级别检查它。我该如何解决这个问题?

仅供参考,这是简化的代码。但是经过广泛的测试,这就是它归结为(99% 肯定)

【问题讨论】:

    标签: typescript class variables callback scope


    【解决方案1】:

    而不是这个:

    this.detectOnElement.addEventListener('touchend', this.resetGestures);
    

    这样做:

    this.detectOnElement.addEventListener('touchend', () => this.resetGestures());
    

    否则,this 不会引用您正在考虑的对象。有关此 JavaScript 行为的更多信息,请点击此处:https://thenewstack.io/mastering-javascript-callbacks-bind-apply-call/

    你也可以显式地bindthis参数:

    this.detectOnElement.addEventListener('touchend', this.resetGestures.bind(this));
    

    更多信息和解释也on this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-25
      • 2022-09-24
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2021-03-05
      • 1970-01-01
      相关资源
      最近更新 更多