JS模式之简单的订阅者和发布者模式完整实例
本文实例讲述了JS模式之简单的订阅者和发布者模式。分享给大家供大家参考。具体如下:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>parten</title>
</head>
<body>
<script>
varsingletonTest=SingletonTest.getInstance({
pointX:5
});
console.log(singletonTest.pointX);
//easy_Observer_model;
functionObserverList(){
this.observerList=[];
};
ObserverList.prototype.Add=function(obj){
returnthis.observerList.push(obj);
};
ObserverList.prototype.Empty=function(){
this.observerList=[];
};
ObserverList.prototype.Count=function(){
returnthis.observerList.length;
};
ObserverList.prototype.Get=function(index){
if(index>-1&&index<this.observerList.length)
returnthis.observerList[index];
};
ObserverList.prototype.Insert=function(obj,index){
varpointer=-1;
if(index==0){
this.observerList.unshift(obj);
pointer=index;
}elseif(index==this.observerList.length){
this.observerList.push(obj);
pointer=index;
};
returnpointer;
};
ObserverList.prototype.IndexOf=function(obj,startIndex){
vari=startIndex,pointer=-1;
while(i<this.observerList.length){
if(this.observerList[i]===obj){
pointer=i;
};
i++
};
returnpointer;
};
ObserverList.prototype.RemoveIndexAt=function(index){
if(index===0){
this.observerList.shift();
}elseif(index===this.observerList.length-1){
this.observerList.pop();
};
returnindex;
};
functionextend(obj,extension){
for(varkeyinobj){
extension[key]=obj[key];
}
};
//
functionSubject(){
this.observers=newObserverList();
};
Subject.prototype.AddObserver=function(obj){
this.observers.add(obj)
};
Subject.prototype.RemoveObserver=function(observer){
this.observers.removeIndexAt(this.observers.IndexOf(observer,0));
};
Subject.prototype.Notify=function(context){
varobserverCount=this.observers.count();
for(vari=0;i<observerCount;i++){
this.observers.Get(i).update(context);
};
}
//Pubsub//subscribe
varPubsub={};
(function(q){
vartopics=[],
subUid=-1;
q.publish=function(topic,args){
if(!topics[topic]){
returnfalse;
};
varsubscribers=topics[topic],
len=subscribers?subscribers.length:0;
while(len--){
subscribers[len].func(topic,args);
}
returnthis;
};
q.subscribe=function(topic,func){
if(!topics[topic]){
topics[topic]=[];
};
vartoken=(++subUid).toString();
topics[topic].push({
token:token,
func:func
});
returntoken;
};
q.unsubscribe=function(token){
for(varmintopics){
if(topics[m]){
for(vari=0;i<topics[m].length;i++){
if(topics[m][i].token===token){
topics[m].splice(i,1);
returntoken;
}
}
};
};
returnthis;
}
})(pubsub);
</script>
</body>
</html>
希望本文所述对大家的javascript程序设计有所帮助。