Learn JavaScript design patterns Observer pattern_javascript skills
May 16, 2016 pm 03:19 PM1. Definition
Observer pattern (publish-subscribe pattern): It defines a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it will be notified.
In JavaScript, the event model is generally used to replace the traditional observer pattern.
Benefits:
- (1) can be widely used in asynchronous programming and is an alternative to passing callback functions.
- (2) can replace the hard-coded notification mechanism between objects. One object no longer needs to explicitly call an interface of another object. The two objects are easily decoupled.
2. DOM events – typical example of observer mode
We need to monitor the user's click action on document.body, but we have no way to predict when the user will click.
Therefore, we subscribe to the click event on document.body. When the body node is clicked, the body node publishes this message to the subscribers!
1 2 3 4 5 6 7 8 9 10 |
|
A certain website has header, nav navigation, message list and other modules. The rendering of these modules requires obtaining user login information.
(1) General writing:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
(2) Using the observer pattern, it is easy to decouple!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
3. Universal Observer Mode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
|
I hope this article will be helpful to everyone learning JavaScript programming.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The difference between design patterns and architectural patterns in Java framework

The wonderful use of the adapter pattern in Java design patterns

Analysis of the Decorator Pattern in Java Design Patterns

PHP design pattern practical case analysis

What are the advantages and disadvantages of using design patterns in java framework?

PHP Design Patterns: Test Driven Development in Practice

Application of design patterns in Guice framework

How design patterns deal with code maintenance challenges
