zoukankan      html  css  js  c++  java
  • js 观察者模式

    观察者模式:定义对象间 一对多 的依赖关系,当一个对象的状态发生改变,所有依赖它的对象都得到通知。

    多人协作在初始化函数init()中不同人都要加事件,直接添加怕出问题,解决团队协作中多人模块间的通信问题,解耦;

    使用:

    1、定义一个发布者

    2、定义发布者的缓存列表,存放回调函数来通知订阅者

    3、遍历缓存列表,触发回调函数 发布消息

    例:简单

    var publisher={};
    publisher.receivers=[];

    publisher.listen=function (fn) {//增加接收者
    this.receivers.push(fn)
    };
    publisher.trigger=function(){//发布消息函数
    for(var i=0;i<this.receivers.length;i++){
    var fn=this.receivers[i];
    fn.apply(this,arguments)
    }
    };
    publisher.listen(function (time) {//某人接收了这个消息
    console.log('正式上班时间:'+time);
    });
    publisher.trigger('2016/10',yes);//发布消息

    // 输出 :正式上班时间:2016/10


    例:
    var Observer=(function () {
    var _rank={};
    return{
    //订阅消息接口
    register:function (type, fn) {
    //如果消息不存在,则放入消息队列
    if(typeof _rank[type]==='undefined'){
    _rank[type]=[fn]
    }else{
    //否则给消息数组添加这个方法
    _rank[type].push(fn)
    }
    },
    //发布消息接口
    fire:function (type, argsJson) {
    if(!_rank[type]){return;}//消息未定义则返回
    var newArgs={
    type:type,
    args:argsJson||{}
    };
    for (var i=0,l=_rank[type].length;i<l;i++){
    _rank[type][i].call(this,newArgs)
    }
    },
    //消息注销方法
    remove:function (type, fn) {
    //确保存在
    if(_rank[type] instanceof Array){
    for(var i=_rank[type].length-1;i>=0;i--){
    //若存在就删除
    _rank[type][i].toString()===fn.toString()
    }
    }
    }
    }
    })();

    Observer.register('eating',function (params) {
    console.log(params.type+':james要吃饭,'+params.args.msg)
    });
    Observer.register('eating',function (params) {
    console.log(params.type+':tom要吃饭,'+params.args.msg)
    });
    Observer.fire('eating',{msg:'**请吃饭'});
    Observer.remove('eating',function (params) {
    console.log(params.type+':amy要吃饭,'+params.args.msg)
    });
    Observer.fire('eating',{msg:"**请吃饭"});
     
  • 相关阅读:
    centos7下编译安装python3.7,且与python2.7.5共存
    Linux下的ctrl常用组合键
    命令 docker rm | docker rmi | docker prune 的差异
    docker操作命令大全和后台参数
    解决Linux下ssh登录后出现 报错 Write failed: Broken pipe 的方法
    在centos7 中docker info报错docker bridge-nf-call-iptables is disabled 的解决方法
    Linux下实现不活动用户登录超时后自动登出
    centos下非yum方式安装docker环境
    Git Error:There is no tracking information for the current branch.
    Vim操作:打开文件
  • 原文地址:https://www.cnblogs.com/redn/p/8087124.html
Copyright © 2011-2022 走看看