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

    什么事观察者模式:

      这是一种创建松散耦合代码的技术。它定义对象间 一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。由主体和观察者组成,主体负责发布事件,同时观察者通过订阅这些事件来观察该主体。主体并不知道观察者的任何事情,观察者知道主体并能注册事件的回调函数。

    代码:

    function EventT(){

      this.handlers = {};

    }

    EventT.prototype = {

      custructor : EventT,

      addHanler : function(type,handler){

        if(typeof this.handlers[type] == 'undefined'){

          this.handlers[type] = [];

        }

        this.handlers[type].push(handler);

      },

      fire:function(event){

        if(!event.target){

          event.target = this;

        }

        if(this.handlers[event.type] instanceof Array){

          var handlers = this.handlers[event.type];

          for(var i=0,len = handlers.length;i<len;i++){

            handlers[i](event)

          }

        }

      },

      removeHandler:function(type,handler){

        if(this.handlers[type] instanceof Array){

          var handlers = this.handlers[type];

          for(var i=0,len=handlers.length;i<len;i++){

            if(handlers[i] === handler){

              break;

            }

          }

          handlers.splice(i,1)

        }

      }

    }

    大概意思就是,创建一个事件管理器。handles是一个存储事件处理函数的对象。

    addHandle:是添加事件的方法,该方法接收两个参数,一个是要添加的事件的类型,一个是这个事件的回调函数名。调用的时候会首先遍历handles这个对象,看看这个类型的方法是否已经存在,如果已经存在则添加到该数组,如果不存在则先创建一个数组然后添加。

    fire方法:是执行handles这个对象里面的某个类型的每一个方法。

    removeHandle:是相应的删除函数的方法。

    新建两个对象:

    var person1 = {};

    var person2 ={};

    Object.assign(person1,Event);

    Object.assign(person2,Event);

    person1.on('call1', function () {
        console.log('person1');
    });
    person2.on('call2', function () {
        console.log('person2');
    });
    person1.emit('call1'); // 输出 'person1'
    person1.emit('call2'); // 没有输出
    person2.emit('call1'); // 没有输出
    person2.emit('call2'); // 输出 'person2'
    原网址:https://www.cnblogs.com/LuckyWinty/p/5796190.html
  • 相关阅读:
    win10下的MyEclipse2017 ci7 破解教程+全套资源+失败处理(转)
    layui layer.open() 弹层开启后 Enter回车 遮罩层无限弹处理
    layui 或者layer 父页面获取子页面数据 或者子页面获取父页面操作方法(转)
    layui弹出层两个以上置顶弹出
    div自动获焦并将光标定位到最后
    hibernate 的SessionFactory的getCurrentSession 与 openSession() 的区别
    形参与实参的区别
    linux下安装Mysql(干货!!!)解决mysql 1130问题,远程登录问题
    linux下安装Mysql(干货!!!)
    java文件上传与下载
  • 原文地址:https://www.cnblogs.com/Mrkaikai/p/9499512.html
Copyright © 2011-2022 走看看