js觀察者模式

來源:互聯網
上載者:User

標籤:

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) {        topics[topic] = topics[topic] ? topics[topic] : [];        var token = (++subUid).toString();        topics[topic].push({            token : token,            func : func        });        return token;    };    //取消訂閱    q.canclesub=function(subtoken){         for (var m in topics) {            if (topics[m]) {                for (var i = 0; i < topics[m].length; i++) {                    if (topics[m][i].token === subtoken) {                        topics[m].splice(i, 1);                        return subtoken;                    }                }            }        }        return false;      }    return q;})();//觸發的事件var logmsg = function(topics, data) {    console.log("logging:" + topics + ":" + data);}//紅眼睛訂閱 ‘wolfcoming‘var a = pubsub.subscribe(‘wolfcoming‘, logmsg);//長耳朵訂閱 ‘wolfcoming‘var b = pubsub.subscribe(‘wolfcoming‘, logmsg);//短尾巴訂閱 ‘wolfcoming‘var c = pubsub.subscribe(‘wolfcoming‘, logmsg);//發布訊息狼來了pubsub.publish(‘wolfcoming‘, ‘狼來了‘);//兔媽媽回來了兔寶寶退訂pubsub.canclesub(a);pubsub.canclesub(b);pubsub.canclesub(c);//發布訊息狼來了pubsub.publish(‘wolfcoming‘, ‘狼來了‘);

  

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.