邮件定阅_观察者形式

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();
    原文作者:zasqw2222
    原文地址: https://segmentfault.com/a/1190000002435053
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞