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:"**请吃饭"});
     
  • 相关阅读:
    JavaScript操作符instanceof揭秘
    Linux打开txt文件乱码的解决方法
    Working copy locked run svn cleanup not work
    poj 2299 UltraQuickSort 归并排序求解逆序对
    poj 2312 Battle City 优先队列+bfs 或 记忆化广搜
    poj2352 stars 树状数组
    poj 2286 The Rotation Game 迭代加深
    hdu 1800 Flying to the Mars
    poj 3038 Children of the Candy Corn bfs dfs
    hdu 1983 Kaitou Kid The Phantom Thief (2) DFS + BFS
  • 原文地址:https://www.cnblogs.com/redn/p/8087124.html
Copyright © 2011-2022 走看看