The trigger sequence of
event snooping is capture phase, target phase, and bubbling phase. In each stage, rather than bubbling phase, we can do event delegation, scenario. For example, a ul has 100 li. If you bind an event on li, do you need to bind it 100 times? but if you use the bubbling mechanism to bind the event to ul, you only need to bind it once and then distinguish it by the event source object. There are many functions, the important thing is to study and ponder more.
should examine the Observer pattern
in the design pattern, mainly for extensibility and code decoupling.
The
Observer pattern creates a abstract
coupling between the observed and the observer. What the observer role knows is a list of concrete observers, and each concrete observer conforms to an abstract observer's interface. The observed does not know any specific observer of
, it only knows that they all have a common interface.
such as updating the interface UI
A method
-> -> UI
B method
UI ()
UI
an actual usage scenario: there is a scheduled task manager (task-scheduler), which scans the tasks that need to be started at the current moment every minute, packages the task information and sends it to Kafka, while the task consumer (task-consumer) listens to different Topic in Kafka to obtain task information for back-end scheduling execution. Here is a good use of the event monitoring mechanism.
so what's the difference between using it or not? When not in use, we need to publish and receive messages through a large number of shared variables, etc. Secondly, task-scheduler will be mixed with task-consumer, the code is complex, and secondly, it is not conducive to the deployment of a single module and highly available implementation, and will affect each other. And what are the benefits of surveillance? You only need to wait for the news to arrive, and you don't need to take the initiative to get the message through rotation training, which is a serious waste of CPU resources.
take another example in the JDK source code: ArrayBlockingQueue has take () and put () methods, which are also similar to the event listening mechanism. When the queue is not empty, you can consume it through take (), otherwise you can block waiting; when the queue is not full, you can use put () to queue up messages, otherwise blocking waiting is not necessary.