邮件订阅_观察者模式

var publisher = {//出版商
            subscribers:{//不同杂志的订阅者数组
                any : [] 
            },
            // 添加订阅这方法
            subscribe:function(fn,type){//订阅是触发的方法和订阅哪个类型的
                type = type || 'any';
                if(typeof this.subscribers[type] === 'undefined'){//如果这个订阅类型没有,就新创建一个
                    this.subscribers[type] = [];
                }
                this.subscribers[type].push(fn);//如果已经存在了,就把订阅触发的方法加到订阅数组里面
            },
            // 删除订阅者
            unsubscribe : function(fn,type){
                this.visitSubscribers('unsubscribe',fn,type);
            },
            // 出版 只有发布者才能出版
            publish : function(publication,type){
                this.visitSubscribers('publish',publication,type);
            },
            //处理删除或者出版的方法
            visitSubscribers : function(action,arg,type){
                var pubtype = type || 'any', //调用哪个订阅者库
                    subscribers = this.subscribers[pubtype],//
                    i,
                    max = subscribers.length;
                    console.log(subscribers)

                    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) && typeof publisher[i] === 'function'){
                o[i] = publisher[i];
            }
        }
        o.subscribers = {
            any : []
        }
    }

    var paper = {
        daily : function(){
            this.publish('paper发行的日刊');
        },
        monthly : function(){
            this.publish('paper发行的月刊','monthly');
        }
    };
    makePublisher(paper); //一个发布者

    var joe = {
        drinkCoffee : function(paper){
            console.log('我读的是' + paper);
        },
        sundayPreNap : function(monthly){
            console.log('我读的是' + monthly);
        }
    }

    paper.subscribe(joe.drinkCoffee);
    paper.subscribe(joe.sundayPreNap,'monthly');

    paper.daily();
    paper.daily();
    paper.daily();
    paper.monthly();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值