JS模式之发布/订阅模式

有时在JS中需要定义特定的事件,这些事件可以传递自定义参数。此时可以采用发布/订阅模式。

发布/订阅模式简单实现如下:

<script type="text/javascript">

var pubsub = {};

(function($) {

  $.topics = {};

  // 发布或广播事件
  $.publish = function (topic, args) {
    if (!$.topics[topic])
      return false;
    if ($.topics[topic] instanceof Array) {
      var topics = $.topics[topic];
      for(var i = 0; i < topics.length; i++)
        topics[i](args);
    }

    return this;
  };

  // 通过特定名称和回调函数订阅事件
  $.subscribe = function (topic, func) {
    if (!$.topics[topic]) 
      $.topics[topic] = [];
    // 对应topic下加入回调函数
    $.topics[topic].push(func);
    return this;
  };

  // 解绑取消订阅事件
  $.unsubscribe = function (topic) {
    if (!$.topics[topic])
      return false;
    delete($.topics[topic]);
    return this;
  }

})(pubsub);

// 注册confirm事件
pubsub.subscribe("confirm", function() {
  alert("this is the confirm");
});

// 注册alert事件 并订阅该事件后取消该订阅
pubsub.subscribe("alert", function(data) {
  alert("this is the alert " + data);
}).publish("alert", "success").unsubscribe("alert");

</script>

 

转载于:https://www.cnblogs.com/yanjliu/p/3958466.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值