JS模式之發布/訂閱模式

來源:互聯網
上載者:User

標籤:style   blog   color   io   java   ar   for   div   cti   

有時在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>

 

JS模式之發布/訂閱模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.