Ionic 2 ionScroll 事件不刷新视图 [英] Ionic 2 ionScroll event to not refresh view
问题描述
我在 <ion-content>
中添加了一个 ionScroll 事件,该事件触发方法 foo()
和
I add to the <ion-content>
a ionScroll event which triggers the method foo()
and in a <button ion-button>
a click event which triggers foo()
too. In my template I add for an example {{ x }}
and the foo()
method increments x
.
按钮单击刷新视图,以便显示新值.滚动没有.如果我添加一个 console.log
这将打印.
The button click refreshs the view so that the new value is shown. The scrolling not. If I add a console.log
this will print.
如果我将 fokus 设置为某个元素,例如文本框或其他元素,则视图会刷新并且 x
的新值会显示出来.
If i set the fokus to some element like a textbox or something, the view refreshs and the new value of x
shows up.
有人知道为什么吗?
推荐答案
这是因为一个非常有趣和强大的东西叫做 Zones.如果这个概念对您来说是新概念,请参考 这里 和 这里很好的解释.
That's because something very interesting and powerfull called Zones. If the concept is new for you, please refer to here and here for a great explanation.
如您所见,
应用程序状态变化是由三件事引起的:
Application state change is caused by three things:
1) 事件 - 用户事件,例如点击、更改、输入、提交……
1) Events - User events like click, change, input, submit, …
2) XMLHttpRequests - 例如从远程服务获取数据时计时器 -
2) XMLHttpRequests - E.g. when fetching data from a remote service Timers -
3) setTimeout(),setInterval(),因为 JavaScript
3) setTimeout(),setInterval(), because JavaScript
... 事实证明,只有这些是 Angular 实际上是有兴趣更新视图.
… it turns out that these are the only cases when Angular is actually interested in updating the view.
这就是为什么当你滚动时视图没有被更新,但是当你触摸页面的任何元素时它会更新(因为它是一个用户事件).
That's why the view is not being updated when you scroll, but it does when you touch any of the elements of the page (since it's a user event).
为了解决这个问题,其中一个选项是让 Angular 知道它需要了解您即将进行的一些更改,因为可能需要更新.您可以通过在区域内运行一些代码(更新 x
属性的代码)来做到这一点,如下所示:
In order to fix this, one of the options is to let Angular know that it needs to be aware of some changes you're just about to make, because things will probably need to be updated. You can do that by running some code (the code that updates the x
property) inside a zone, like this:
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!
});
}
}
这篇关于Ionic 2 ionScroll 事件不刷新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!