JavaScript設計模式之觀察者模式

觀察者模式(訂閱發佈模式)

該模式廣泛應用於客戶端程序,促進鬆散耦合

//通用發佈者對象
var publisher = {
    subsribers: {  
      any: []//通用訂閱者方法
    },
    subscribe: function (fn,type) {  
      type = type || 'any';

      if(!this.subscribers[type]){
          this.subscribers[type] = [];
      }
      this.subscribers[type] = fn;
    },
    unsubscribe: function (fn,type) {
        this.visitSubscribers('unsubscribe',fn,type);
    },
    publish: function (fn,type) {
        this.visitSubscribers('publish',fn,type);
    },
    visitSubscribers: function (action,arg,type) {
        var pubtype = type || 'any',
                subscribers = this.subscribers[pubtype],
                I,
                max = subscribers.length;

        for(I = 0;i < max;i ++ ){
            if(action === 'publish'){
                subscribers[I](arg);
            }else{
                if(subscribers[I] === arg){
                    subscribers.splice(i,1);
                }
            }
        }
    }
}
//將普通對象變成訂閱者的函數
Function makePublisher(o) {
    var I;

    for(I in publisher){
        if(publisher.hasOwnProperty(i)){  
          o[i] = publisher[I];
        }
    }

    o.subscribers = {any: []};
}

//示例,一個paper對象
Var paper = {
    daily: function () {
        this.publish('big news today');
    },
    monthly: function () {
        this.publish('interesting analysis','monthly')
    }
};

//將paper轉換成一個發佈者
makePublisher(paper);

//訂閱者對象
Var Joe = {
    drinkCoffee: function (paper) {
        console.log('Just read ' + paper)
    },
    sundayPreNap: function (paper) {  
        console.log('About to fall asleep reading this ' + paper);
    }
};
//訂閱Paper
Publisher.subscribe(Joe.drinkCoffee);
Publisher.subscribe(Joe.sundayPreNap,'monthly');

//觸發事件
Publisher.daily();
Publisher.daily();
Publisher.daily();
Publisher.monthly();

>Just read big news today
>Just read big news today
>Just read big news today
>About to fall asleep reading this interesting analysis

//現在實現雙向訂閱
makePubliser(Joe);
Joe.tweet = function (msg) {  
      this.publish(msg);
}

//paper反過來去訂閱Joe的推特
Paper.readTweets = function (tweet) {  
    alert('Call big meeting someone ' + tweet);
}
Joe.subscribe(paper.readTweets);
//只要joe發推特paper就會收到信息
Joe.tweet('hated the paper today');
>Call big meeting someone hated the paper today
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章