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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值