发布订阅和观察者模式

发布订阅模式和观察者模式

var dom= document.getElementById('dom');
dom.onclick = function(){}; Dom一级事件 相当于观察者模式
dom.addEventListener('click',function(){}); Dom二级事件,相当于发布订阅,会有一个事件池,存放注册的回调

观察者模式

观察者模式: 观察者(Observer)直接订阅(Subscribe)主题(Subject),而当主题被激活的时候,会触发(Fire Event)观察者里的事件。

** 重点为B直接订阅主题A,AB之间存在直接依赖 **


//观察者对象
var Observer = function(){
    this.notify = function(_fn){

    }
}
//发布消息对象
var Publisher = function(_data){
    this.event = _data;
    this.subscribes = [];
    this.subscribe = function(_fn){
        this.subscribes.push(_fn);
    };
    this.unsubscribe = function(_fn){
        var arr = this.subscribes, len =arr.length;
        for (let index = 0; index < len; index++) {
            if(_fn === arr[index]){
                arr.splice(index,1);
            }
        } 
    }
    this.fire = function(_s){
        var arr = this.subscribes, len =arr.length;
        for (let index = 0; index < len; index++) {
            if(typeof( arr[index]) === 'function'){
                arr[index](this.event,...arguments);
            }
        }
    }
}

var pub =  new Publisher('这是一个手机通知事件,整点抢购');

// 处理函数
function notify1(_e,_e1){
    console.log(_e,_e1);
}

function notify2(_e,_e1){
    console.log(_e,_e1);
}

// 订阅事件
pub.subscribe(notify1);

pub.subscribe(notify2);

后记 也可以将观察者进行对象封装 ,传入的不再是一个函数,还是一个对象,其中提供了notify的方法用来通知自己。

发布订阅模式

订阅者(Subscriber)把自己想订阅(Subscribe)的事件注册到调度中心(Topic),当发布者(Publisher)发布该事件(Publish topic)到调度中心,也就是该事件触发时,由调度中心统一调度(Fire Event)订阅者注册到调度中心的处理代码。

  var CallBack = function (_data) {
    this.event = _data;
    this.subscribes = {};
    this.subscribe = function (topic, _fn) {
        if (!this.subscribes[topic]) {
            this.subscribes[topic] = [];
        }
        this.subscribes[topic].push(_fn);
    };
    this.unsubscribe = function (topic, _fn) {
        var $topic = this.subscribes[topic], len = $topic.length;
        if ($topic) {
            for (let index = 0; index < len; index++) {
                if (_fn === $topic[index]) {
                    $topic.splice(index, 1);
                }
            }
        }else{
            console.log('not this topic =>'+topic)
        }

    }
    this.fire = function (topic,_s) {
        var $topic = this.subscribes[topic];;
        if ($topic) {
            var  len = $topic.length
            for (let index = 0; index < len; index++) {
                if(typeof($topic[index]) !== 'function')continue;
                $topic[index](this.event, ...arguments)

            }
        }else{
            console.log('not this topic =>'+topic)
        }
    }
}

var callBack = new CallBack('这是一个手机通知事件,整点抢购');

callBack.subscribe('抢购',notify1);

callBack.subscribe('抢购',notify2);


posted @ 2020-04-01 19:02  古月大叔  阅读(242)  评论(0编辑  收藏  举报