Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - How does AngularJS's $watch function work?

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.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

See 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.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...