function Observer(){
this.handles = {};
}
Observer.prototype = {
subscribe:function(type,handle){
if(!this.handles[type]){
this.handles[type] = [];
}
this.handles[type].push(handle);
},
unsubscribe:function(type,handle){
var listener = this.handles[type];
if(listener){
if(!handle){
listener.length = 0;
}else{
for(var i = 0;i < listener.length;i++){
if(listener[i] === handle){
listener.splice(i,1);
}
}
}
}
},
publish:function(type,event){
if(!this.handles[type]){
return false;
}
for(var i = 0;i < this.handles[type].length;i++){
var handle = this.handles[type][i];
handle(event);
}
}
}
var p = new Observer();
var fn = function(name){
console.log('mm:'+name);
}
p.subscribe('mm',fn);
p.publish('mm','123321'); //"mm:123321"
复制代码
关键点:
- 注意发布者和订阅者之间的关系是通过发布者上的一个对象来建立交互的,即handles
- 订阅者本质上是一个函数(javascript中函数也是一个对象)
- 订阅,取消订阅,发布的功能都在发布者身上,订阅者只是通过依附(attach)或者脱离(disattach)来订阅或者退订事件