【问题标题】:Will $timeout/setTimeout callback function executes before UI updates?$timeout/setTimeout 回调函数会在 UI 更新之前执行吗?
【发布时间】:2023-03-22 13:28:01
【问题描述】:

这个问题实际上是在我用 AngularJS 1.6.10 编写时发生的,但我认为 $timeout 在某种程度上是 setTimout,所以我提到了两者。

长话短说,我有两个divs 可以根据使用ng-if 的条件进行切换

<div ng-if="!vm.isDrillDowned" id="{{vm.segContainerId}}" style="height: 100%; width: 100%;"></div>
<div ng-if="vm.isDrillDowned" id="{{vm.drillDownContainerId}}" style="height: 100%; width: 100%;">

控制ng-if条件的代码是:

public renderReport(filters){   
    if (//some condition) {
        reportId = this.drillDownId;
        containerId = this.drillDownContainerId;
        this.isDrillDowned = true;
    }

    if (//some condition) {
        reportId = this.segId;
        containerId = this.segContainerId;
        this.segmentFilter = null;
        this.isDrillDowned = false;
    }
    //Expect $timeout to refresh UI showing one div, then runs this.render()
    this.$timeout(() => this.render(reportId, containerId, filtersCopy));
}

this.render()

public render(reportId: string, containerId: string, filters?: any) {
    const container = document.querySelector(`#${containerId}`);
    this.$window.ThirdPartySDK.renderReportPart(container, /*other parameters */);
}

当我调试的时候,有时当代码在$timeout里面碰到函数时,我可以看到isDrilledDown被改变了,但是ng-if还没有刷新视图,所以querySelector可以'找不到与containerId相关的DOM元素。

根据 JS 的事件循环和 $timeout/setTimeout 的机制,我假设 this.render 只会在 UI 更新后运行,但有时并非如此。 ng-class 在另一个地方也发生了同样的问题,在 $timeout 内运行时元素类不会更新。

我只是想知道在某些极端情况下这种行为是否可能?我所搜索的只是说 $timeout/setTimeout 将在 UI 更新后运行它的回调。

提前致谢!

【问题讨论】:

    标签: javascript angularjs settimeout


    【解决方案1】:

    如果不是这样,我深表歉意。但是我是新人,所以我没有声誉点可以评论。

    您的函数声明是独一无二的。我不知道可以或应该从函数的参数运行代码。

    也许这只是一个复制/粘贴错误。

    【讨论】:

    • 你的意思是$timeout()吗?如果是,$timeout 接受函数类型的第一个参数,我所做的是传递一个匿名函数。您可以单独定义它并使用函数名称传递它。
    • 不,我指的是这一行 public renderReport(filters?: 。没有右括号。不过,这可能只是一个错字。
    猜你喜欢
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2021-08-15
    • 2021-08-02
    • 2013-01-27
    相关资源
    最近更新 更多