Home > Article > Web Front-end > A simple example of publish/subscribe pattern in JavaScript_javascript tips
Last time I studied the observer mode, many articles said that it is also called Subscribe/Publish (publish/subscribe mode). But in the book "Javascript Design Patterns", there are still some differences between these two patterns. The original words in the book are as follows:
1. The Observer mode requires that observers who wish to receive topic notifiers must subscribe to content change events.
2.Subscribe/Publish mode uses a topic/event channel, which is between subscribers and publishers. The event system allows code to define application-specific events that can be passed custom parameters that contain values required by subscribers. Its purpose is to avoid dependencies between subscribers and publishers.
Different from the Observer pattern in that it allows any subscriber to execute appropriate event handlers to register and receive notifications from the publisher.
Okay, I don’t know. The following is my understanding:
1. In the observer pattern, the target object is responsible for maintaining the observer. In the publish/subscribe model, the publisher does not care about the subscribers and is only responsible for throwing out the messages.
2. In the observer pattern, the observer must provide an interface, and then call this interface when the target object changes to keep its own state consistent with the target state. That is, all observers must have a unified interface (such as the update method written above, everyone's method must be called this name). In the publish/subscribe model, the triggering of subscriber events does not rely on such an interface, but is triggered by the subscriber by listening to a specific message (this message generally contains the name and parameters required by the subscriber). It can be understood that what the subscriber monitors is not the publisher, but the message pool. As long as there is a message it cares about in the message pool, an event is triggered, regardless of who published the message. Publishers and subscribers are decoupled.
The following is the implementation of the publish/subscribe mode in js. Copy and paste it into the console and give it a try: