zoukankan      html  css  js  c++  java
  • 观察者模式(订阅-发布者模式)

    class Observer{
    	constructor(){
    		this._dataStore = {};
    	}
    	
    	/**
    	 * @author web得胜
    	 * @param {String} type 事件类型	必填
    	 * @param {Function} fn 事件处理函数	必填
    	 * @param {Object} ctx 函数的执行上下文	选填
    	 * @desc 注册事件处理函数
    	 * */
    	regist(type, fn, ctx=null){
    		if(this._dataStore[type]){
    			this._dataStore[type].push({fn,ctx});
    		}else{
    			this._dataStore[type] = [{fn,ctx}];
    		}
    	}
    	
    	/**
    	 * @author web得胜
    	 * @param {String} type 事件类型	必填
    	 * @param {*} 处理函数的参数列表	选填
    	 * @desc 触发事件
    	 * */
    	fire(type, ...args){
    		console.log(args);
    		this._dataStore[type].forEach((item,index) => {
    			item.fn.call(item.ctx, ...args);
    		});
    	}
    	
    	/**
    	 * @author web得胜
    	 * @param {String} type 事件类型	必填
    	 * @param {Function} fn 事件处理函数	必填
    	 * @desc 移除事件处理函数
    	 * */
    	remove(type, fn){
    		if(this._dataStore[type]){
    			this._dataStore[type].forEach((item,index) => {
    				if(item.fn === fn){
    					this._dataStore[type].splice(index,1);
    				}
    			});
    		}
    	}
    }
    

      

    function solid(){
    	console.log(this.name);
    }
    
    function zds(){
    	console.log(this.name);
    }
    
    function fzy(arg1,arg2,arg3){
    	console.log(arguments);
    }
    
    const ob = new Observer();
    const solidCtx = { name: "solid" };
    const zdsCtx = {name: "zds" };
    
    // 注册事件
    ob.regist("click", solid, solidCtx);
    ob.regist("click", zds, zdsCtx);
    ob.regist("dblclick", fzy);
    
    // 移除事件
    // ob.remove("click",zds);
    
    // 触发(发布)事件
    ob.fire("click");
    ob.fire("dblclick",1,2,3);
    

      

  • 相关阅读:
    Python笔记(六)- 模型及Django站点管理
    Python笔记(五)--Django中使用模板
    Java中对象的复制
    Echarts堆积柱状图排序问题
    java基础
    java中的重载与重写
    struts2中配置文件的调用顺序
    struts2的工作原理
    拦截器和过滤器的区别
    Struts2中访问web元素的四种方式
  • 原文地址:https://www.cnblogs.com/zhaodesheng/p/10956149.html
Copyright © 2011-2022 走看看