Skip to content

Commit 32f318a

Browse files
committed
Add additional information for command
1 parent a55ed78 commit 32f318a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -830,6 +830,43 @@ The different handlers from the UML diagram above are the different scopes, inje
830830
831831
![Command](./images/command.png "Fig. 11")
832832

833+
Before continuing with the application of the command pattern lets describe how AngularJS implements data binding.
834+
835+
When we want to bind our model to the view we use the directives `ng-bind` (for single-way data binding) and `ng-model` (for two-way data binding). For example, if we want each change in the model `foo` to reflect the view we can:
836+
837+
```html
838+
<span ng-bind="foo"></span>
839+
```
840+
841+
Now each time we change the value of `foo` the inner text of the span will be changed. We can achieve the same effect with more complex AngularJS expressions, like:
842+
843+
```html
844+
<span ng-bind="foo + ' ' + bar | uppercase"></span>
845+
```
846+
847+
In the example above the value of the span will be the concatenated uppercased value of `foo` and `bar`. What happens behind the scene?
848+
849+
Each `$scope` has method called `$watch`. When the AngularJS compiler find the directive `ng-bind` it creates a new watcher of the expression `foo + ' ' + bar | uppercase`, i.e. `$scope.$watch("foo + ' ' + bar | uppercase", function () { /* body */ });`. The callback will be triggered each time the value of the expression change. In the current case the callback will update the value of the span.
850+
851+
Here are the first a couple of lines of the implementation of `$watch`:
852+
853+
```javascript
854+
$watch: function(watchExp, listener, objectEquality) {
855+
var scope = this,
856+
get = compileToFn(watchExp, 'watch'),
857+
array = scope.$$watchers,
858+
watcher = {
859+
fn: listener,
860+
last: initWatchVal,
861+
get: get,
862+
exp: watchExp,
863+
eq: !!objectEquality
864+
};
865+
//...
866+
```
867+
868+
We can think of the `watcher` object as a command. The expression of the command is being evaluated on each `"$digest"` loop, once AngularJS detects change it invokes the `listener` function. The `watcher` command encapsulates the whole information required for watching the given expression and delegates the execution of the command to the `listener` (the actual receiver). We can think of the `$scope` as the command `Client` and the `$digest` loop as command `Invoker`.
869+
833870
### Controllers
834871
835872
#### Page Controller

0 commit comments

Comments
 (0)