亲宝软件园·资讯

展开

js订阅发布者模式 js实现的订阅发布者模式简单示例

VRlook 人气:0

本文实例讲述了js实现的订阅发布者模式.分享给大家供大家参考,具体如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    var pubsub = (function(){
      var q = {}
        topics = {},
        subUid = -1;
      //发布消息
      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;
      };
      //订阅事件
      //接收两个参数 要订阅的话题,处理程序
      q.subscribe = function(topic, func) {
        //如果当前话题已经有订阅者,获取到订阅者数组
        //一个话题名下的 订阅者事件可以是多个fn1, fn2, fn3
        topics[topic] = topics[topic] ? topics[topic] : [];
        
        //给每个订阅者添加唯一的token
        var token = (++subUid).toString();
        topics[topic].push({
          token : token,
          func : func
        });
        return token;
      };
      //取消订阅
      q.unsubscribe = function(token){
        Object.keys(topics).map( key => {
          topics[key].map((fn, fnIndex) => {
            if(fn.token == token){
              topics[key].splice(fnIndex,1)
            }
          })
        })
      }
      return q;
    })();
    //触发的事件(订阅者的处理程序)
    var logmsg1 = function(topics, data) {
      console.log("logging1:" + topics + ":" + data);
    }
 
    var logmsg2 = function(topic, data) {
      
      console.log("logging2:" + topic + ":" + data,'我是订阅者2');
    }
    //监听指定的消息'msgName'
    var sub1 = pubsub.subscribe('msgName', logmsg1);
    var sub2 = pubsub.subscribe('msgName', logmsg2);
    //pubsub.unsubscribe(sub1)
    //发布消息'msgName'
    pubsub.publish('msgName', 'hello world');
    //发布无人监听的消息'msgName1'
    pubsub.publish('anotherMsgName', 'me too!');
  </script>
</body>
</html>

运行结果:

希望本文所述对大家JavaScript程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论