A simple example of the publish and subscribe pattern in JavaScript

  • 2020-03-30 04:14:27
  • OfStack

Last time I looked at the observer pattern, many articles said it was also called Subscribe/Publish. However, in the book Javascript design patterns, there are some differences between the two patterns. The text is as follows:

2. The Subscribe/Publish pattern USES a topic/event channel between subscribers and publishers. The event system allows code to define application-specific events that can pass custom parameters containing the values required by subscribers. The goal is to avoid dependencies between subscribers and publishers.

Unlike the Observer pattern, it allows any subscriber to perform appropriate event handlers to register and receive notifications from publishers.

Okay, I don't know. Here's what I understand:

1. In observer mode, the target object is responsible for maintaining the observer. In publish/subscribe, the publisher doesn't care about the subscriber, just throws the message out.

2. In observer mode, the observer provides an interface, which is then invoked when the target object changes to keep its state consistent with the target state. That is, all observers should have a unified interface (such as the update method written above, which is the name of everyone's method). In publish/subscribe mode, subscriber events are triggered not by such an interface, but by the subscriber listening to a particular message, which typically contains the name and parameters required by the subscriber. It can be understood that the subscriber is not listening to the publisher, but to the message pool, regardless of who posted the message, as long as the pool has the message it CARES about, the trigger event. Publishers and subscribers are decoupled.

The following is the implementation of publish/subscribe mode in js, copy and paste it into the console as soon as you try it:


var pubsub = (function(){
    var q = {}
        topics = {},
        subUid = -1;
    //Publish message
    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;
    };
    //Subscription event
    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;
    //Unsubscribe and not write, iterate over topics, and then delete the specified
element by saving the previous return token })();
//
var logmsg = function(topics, data) {
    console.log("logging:" + topics + ":" + data);
}
//Listen for 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 articles: