Observer(观察者)是一种设计模式,一个对象(subject)维持一系列依赖于它(观察者)的对象,将任何状态的任何变更自动通知给它们。
Suject(目标)
维护一系列的观察者,方便添加或者删除观察者。
Observer(观察者)
为那些在目标状态发生改变时需获得通知的对象提供更新接口
function ObserverList(){ this.observerList=[]; } ObserverList.prototype.Add=function(obj){ return this.observerList.push(obj); }; ObserverList.prototype.RemoveIndexAt=function(index){ this.observerList.splice(index,1); }; ObserverList.prototype.Count=function(){ return this.observerList.length; }; ObserverList.prototype.Get=function(index){ if(index > -1 && index < this.observerList.length){ return this.observerList[index]; } };
function Subject(){ this.observers=new ObserverList(); } Subject.prototype.AddObserver=function(observer){ this.observers.Add(observer); }; Subject.prototype.RemoveObserver=function(observer){ this.observers.RemoveIndexAt(this.observers.indexOf(observer)); } Subject.prototype.Notify=function(context){ var observerCount=this.observers.Count(); for(var i= 0; i < observerCount; i++){ this.observers.Get(i).Update(context); } }
function Observer(){ this.Updata=function(){ //具体的操作 } }
Observer模式一般会使用一个成为Publish/Subscribe模式的变量来实现。Publish/Subscribe模式使用的是主题/事件通道,这个通道介于希望接收到通知的对象(订阅者)和激活事件的对象(发布者)之间。该事件系统允许代码自定义应用程序的特定事件,这些事件乐意传递自定义参数,自定义参数包含订阅者所需的值,其目的是避免订阅者和发布者之间产生关系。
var pubsub={}; (function(q){ var topics={}, subUid=-1, subscribers, len; //发布广播事件,包含特定的topic名称和参数 q.publish=function(topic, args){ if(!topics[topic]){ return false; } subscribers=topics[topic]; len=subscribers ? subscribers.length : 0; while(len--){ subscribers[len].func(topic, args); } return this; }; q.subscribe=function(topic, func){ if(!topics[topic]){ topics[topic]=[]; } var token=(++subUid).toString(); topics[topic].push({ token:token, func:func }); return token; }; q.unsubscribe=function(token){ for(var m in topics){ if(topics[m]){ for(var i = 0, j=topics[m].length; i < j; i++){ if(topics[m][i].token === token){ topics[m].splice(i, 1); return token; } } } } return this; }; })(pubsub);
function log1(topic ,data){ console.log(topic , data) } function log2(topic ,data){ console.log("Topic is "+topic+" Data is "+data); } pubsub.subscribe("sss",log1); pubsub.subscribe("cccc",log2); pubsub.publish("sss","aaaaa1"); pubsub.publish("sss","aaaaa2"); pubsub.publish("cccc","ssssss");