Home > Web Front-end > JS Tutorial > body text

A simple example of publish/subscribe pattern in JavaScript_javascript tips

WBOY
Release: 2016-05-16 16:32:08
Original
1234 people have browsed it

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:

Copy code The code is as follows:

var pubsub = (function(){
var q = {}
topics = {},
        subUid = -1;
//Publish news
​ q.publish = function(topic, args) {
If(!topics[topic]) {return;}
      var subs = topics[topic],
            len = subs.length;
​​​​while(len--) {
              subs[len].func(topic, args);
}
         return this;
};
//Subscribe to events
​ q.subscribe = function(topic, func) {
topics[topic] = topics[topic] ? topics[topic] : [];
      var token = ( subUid).toString();
topics[topic].push({
token : token,
              func : func
        });
         return token;
};
Return q;
//No more writing if you cancel the subscription, traverse the topics, then return the token by saving it, and delete the specified element
})();
//Triggered event
var logmsg = function(topics, data) {
console.log("logging:" topics ":" data);
}
//Listen to the specified message 'msgName'
var sub = pubsub.subscribe('msgName', logmsg);
//Publish message 'msgName'
pubsub.publish('msgName', 'hello world');
//Publish an unmonitored message 'msgName1'
pubsub.publish('anotherMsgName', 'me too!');
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template