发布/订阅,是一种由两个部分构成:发布者和订阅者的消息传递模式。发布者将消息发布到特定频道,而订阅者接听频道,当频道上有消息发布时将接收到通知。
1、用javascript实现Pub/Sub模式代码:
1 var PubSub = { 2 //订阅 3 subscribe : function(ev,callback){ 4 this._callback || (this._callback = {}); 5 (this._callback[ev] || (this._callback[ev] = [])).push(callback); 6 return this; 7 }, 8 //取消订阅 9 unsubscribe : function(ev){ 10 if(!this._callback || !this._callback[ev]){ 11 return this; 12 } 13 this._callback[ev] = null; 14 delete this._callback[ev]; 15 return this; 16 }, 17 //发布 18 publish : function(){ 19 var callback, list, i, length, args = [].slice.call(arguments,0), ev = args.shift(); 20 if(!(callback = this._callback) || !(list = this._callback[ev])){ 21 return this; 22 } 23 for(i = 0, length = list.length; i < length; i++){ 24 list[i].apply(this, args); 25 } 26 return this; 27 } 28 }; 29 PubSub.subscribe('wen',function(){alert('Wen!!!');}).publish('wen').unsubscribe('wen').publish('wen');