美文网首页工作生活
订阅发布模式

订阅发布模式

作者: 恒星的背影 | 来源:发表于2019-07-04 10:36 被阅读0次

    pubsub.js

    let subscribers = {};
    
    module.exports = {
        publish(event, data) {
            if(subscribers[event])
              subscribers[event].forEach(cb => cb(data));
        },
        subscribe(event, callback) {
          if (!subscribers[event]) {
              subscribers[event] = [];
          }
          subscribers[event].push(callback)
    
          let index = subscribers[event].length - 1;
          return {
              unsubscribe() {
                  subscribers[event].splice(index, 1);
              }
          };
        }
    };
    

    moduleA.js

    const pubSub = require("./pubsub");
    module.exports = {
        publishEvent() {
            pubSub.publish("anEvent", {
              msg: "TOP SECRET DATA"
            });
        }
    };
    

    moduleB.js

    const pubSub = require("./pubsub");
    
    let subscription = pubSub.subscribe("anEvent", data => {
      console.log(`"anEvent", was published with this data: "${data.msg}"`);
      subscription.unsubscribe();
    });
    

    index.js

    const moduleA = require("./moduleA");
    require("./moduleB");
    
    moduleA.publishEvent();
    moduleA.publishEvent();
    

    参考目录

    JavaScript Design Patterns Part 2: The Publisher/Subscriber Pattern

    相关文章

      网友评论

        本文标题:订阅发布模式

        本文链接:https://www.haomeiwen.com/subject/dxxhhctx.html