You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
>The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
There are two basic ways of communication between the scopes in an AngularJS application. The first one is calling methods of parent scope by a child scope. This is possible since the child scope inherits prototypically by its parent, as mentioned above (see [Scope](#scope)). This allows communication in a single direction - child to parent. Some times it is necessary to call method of given child scope or notify it about a triggered event in the context of the parent scope. AngularJS provides built-in observer pattern, which allows this. Another possible use case, of the observer pattern, is when multiple scopes are interested in given event but the scope, in which context the event is triggered, is not aware of them. This allows decoupling between the different scopes, non of the scopes should be aware of the rest of the scopes.
Each AngularJS scope has public methods called `$on`, `$emit`and`$broadcast`. The method `$on`accepts topic as first argument and callback as second. We can think of the callback as an observer - an object, which implements the `Observer`interface (in JavaScript the functions are first-class, so we can provide only implementation of the `notify`method):
In this way the current scope "subscribes" to events of type `event-name`. When`event-name`is triggered in any parent or child scope of the given one, `handler`would be called.
The scope in the example above, triggers the event `event-name`to all scopes upwards. This means that each of the parent scopes of the given one, which are subscribed to the event `event-name`, would be notified and their handler callback will be invoked.
Analogical is the case when the method `$broadcast`is called. The only difference is that the event would be transmitted downwards - to all children scopes.
823
-
Each scope can subscribe to any event with multiple callbacks (i.e. it can associate multiple observers to given event).
0 commit comments