AngularJS 的 $watch 函数是如何工作的? [英] How does AngularJS's $watch function work?

查看:21
本文介绍了AngularJS 的 $watch 函数是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在读了很多关于 AngularJS 的书,我发现了那个神奇的 $watch 函数.我知道如何使用它,但我想知道它是如何在后台实现的.是时间间隔函数吗?还是 Angular 会在每条语句执行时调用此手表?

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?

我现在不想深入研究源代码,如果你们中的一个人已经知道答案并想分享他关于该主题的知识,我会很高兴.

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.

谢谢.

推荐答案

所有 watch 都会在每个摘要循环中进行评估(有时是多次).摘要循环是由于某些事件或调用 $apply() 而进入的.手表不会根据计时器定期调用.

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.

参见 https://docs.angularjs.org/guide/scope#与浏览器事件循环集成

浏览器的事件循环等待事件到达.事件的回调被执行...一旦回调执行,浏览器离开 JavaScript 上下文并根据 DOM 更改重新渲染视图.Angular 通过提供自己的事件处理循环来修改正常的 JavaScript 流程.这将 JavaScript 分为经典执行上下文和 Angular 执行上下文……Angular 执行 [某些] 刺激 Fn(),这通常会修改应用程序状态.Angular 进入 $digest 循环.该循环由两个较小的循环组成,它们处理 $evalAsync 队列和 $watch 列表.$digest 循环不断迭代,直到模型稳定下来,这意味着 $evalAsync 队列为空并且 $watch 列表未检测到任何更改.$watch 列表是一组自上次迭代以来可能已更改的表达式.如果检测到更改,则调用 $watch 函数,该函数通常使用新值更新 DOM.

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.

这篇关于AngularJS 的 $watch 函数是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆