javascript AngularJS 的 $watch 函数是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18634666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does AngularJS's $watch function work?
提问by SRachamim
I'm reading a lot about AngularJS nowadays, and I came across that magical $watch function. I understand how to use it, but I wonder how is it implemented in the background. Is it a time interval function? Or is it Angular calling this watch every statement executed?
我现在读了很多关于 AngularJS 的书,我遇到了神奇的 $watch 函数。我知道如何使用它,但我想知道它是如何在后台实现的。是时间间隔函数吗?或者是 Angular 在每条语句执行时都调用这个手表?
I don't want to dig into the source code right now, and I would glad if one of you already know the answer and want to share his knowledge about the subject.
我现在不想深入研究源代码,如果你们中的一个人已经知道答案并想分享他关于该主题的知识,我会很高兴。
Thanks.
谢谢。
回答by Mark Rajcok
All watches are evaluated (sometimes multiple times) every digest loop. The digest loop is entered as a result of some event, or calling $apply(). Watches are not called periodically based on a timer.
每个摘要循环都会评估所有监视(有时多次)。摘要循环是由于某些事件或调用 $apply() 而进入的。手表不是基于计时器定期调用的。
See https://docs.angularjs.org/guide/scope#integration-with-the-browser-event-loop
请参阅https://docs.angularjs.org/guide/scope#integration-with-the-browser-event-loop
The browser's event-loop waits for an event to arrive. The event's callback gets executed... Once the callback executes, the browser leaves the JavaScript context and re-renders the view based on DOM changes. Angular modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and Angular execution context... Angular executes [some] stimulusFn(), which typically modifies application state. Angular enters the $digest loop. The loop is made up of two smaller loops which process $evalAsync queue and the $watch list. The $digest loop keeps iterating until the model stabilizes, which means that the $evalAsync queue is empty and the $watch list does not detect any changes. The $watch list is a set of expressions which may have changed since last iteration. If a change is detected then the $watch function is called which typically updates the DOM with the new value.
浏览器的事件循环等待事件到达。事件的回调被执行...一旦回调执行,浏览器离开 JavaScript 上下文并根据 DOM 更改重新渲染视图。Angular 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 分为经典执行上下文和 Angular 执行上下文……Angular 执行 [某些] 刺激 Fn(),这通常会修改应用程序状态。Angular 进入 $digest 循环。该循环由两个较小的循环组成,它们处理 $evalAsync 队列和 $watch 列表。$digest 循环不断迭代,直到模型稳定,这意味着 $evalAsync 队列为空并且 $watch 列表未检测到任何更改。$watch 列表是一组自上次迭代以来可能已更改的表达式。