Ionic 2 ionScroll 事件不刷新视图

Ionic 2 ionScroll event to not refresh view

我在 <ion-content> 中添加了一个触发方法 foo() 的 ionScroll 事件,在 <button ion-button> 中添加了一个也会触发 foo() 的点击事件。在我的模板中,我添加了一个示例 {{ x }} 并且 foo() 方法递增 x.

单击按钮会刷新视图,以便显示新值。滚动没有。如果我添加 console.log 这将打印。

如果我将 fokus 设置为文本框之类的某个元素,视图会刷新并显示 x 的新值。

有人知道为什么吗?

那是因为一个非常有趣和强大的东西叫做 Zones。如果这个概念对您来说是新的,请参阅 here and here 以获得很好的解释。

如您所见,

Application state change is caused by three things:

1) Events - User events like click, change, input, submit, …

2) XMLHttpRequests - E.g. when fetching data from a remote service Timers -

3) setTimeout(),setInterval(), because JavaScript

… it turns out that these are the only cases when Angular is actually interested in updating the view.

这就是为什么当您滚动时视图不会更新,但当您触摸页面的任何元素时它会更新(因为它是用户事件)。

为了解决这个问题,其中一个选项是让 Angular 知道它需要了解您即将进行的一些更改,因为可能需要更新一些内容。您可以通过 运行 区域中的一些代码(更新 x 属性 的代码)来做到这一点,如下所示:

import { Component, NgZone } from '@angular/core';

@Component({...})
export class MyPage {

    constructor(..., private ngZone: NgZone) {}

    public yourMethod(): void {
        this.ngZone.run(() => {
            // Update the x property here, and the view will be updated!
        });
    }
}