Monitoring Object properties: $watch and $digest
$watch and $digest are mutually reinforcing. Together, they form the core of the angular scope: response to data changes. If you have studied WPF and used some MVVM frameworks based on WPF, then you must know that the INotifyPropertyChanged interface will allow our objects to notify the UI when the data changes, to present the latest data. $watch and $digest are actually the same principle.
With $watch, you can add a listener to the scope. The listener receives a prompt when a change occurs on the scope. You can create a listener by specifying the following two functions for $watch:
(1), a monitoring function for specifying the part of the data that you are interested in
(2), a listener function, to accept the prompt when the data changes.
As a angular user, it is generally the monitoring of an expression rather than the use of a monitoring function. A monitoring expression is a string, such as "User.firstname", usually specified in data binding, instruction properties, or JavaScript code, which is parsed and compiled angular into a monitoring function. In the later part of this article we will explore how this is done. In this article, we'll use a slightly lower-level approach to providing monitoring capabilities directly.
In order to implement $watch, we need to store all registered listeners. We add an array on the scope constructor:
function Scope () { this. $ $watchers = [];}
In the angular framework, the double-dollar character prefix $$ indicates that the variable is considered private and should not be called in external code.
Now we can define the $watch method. It takes two functions as arguments and stores them in the $ $watchers array. We need to store these functions on each scope instance, so put it on the scope's prototype:
function (WATCHFN, LISTENERFN) { var watcher = { watchfn:watchfn, LISTENERFN:LISTENERFN }; This . $ $watchers. push (watcher);};
The other side is the $digest function. It performs all the listeners that have been registered on the scope. Let's implement a simplified version of it, traverse all the listeners, and invoke their listener functions:
function () { _.foreach (thisfunction(watch) { watch.listenerfn (); }); };
Now we can add the listener and then run $digest, which will invoke the listener function.
These are not very much in themselves, we want to be able to detect whether the value specified by the monitoring function is actually changed, and then invoke the listener function.
AngularJS Monitoring Object properties: $watch and $digest