标签:
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‘, ‘狼来了‘);
标签:
原文地址:http://www.cnblogs.com/bweb/p/5754225.html