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);
    

      

  • 相关阅读:
    站立会议(二)
    站立会议(一)
    买书优惠问题
    软件的NABCD----安装部分
    你的灯亮着吗读书笔记(一)
    软件工程概论---环状二维数组最大子数组和
    梦断代码读书笔记(三)
    梦断代码读书笔记(二)
    课程作业3.10
    软件工程作业提交3.06
  • 原文地址:https://www.cnblogs.com/zhaodesheng/p/10956149.html
Copyright © 2011-2022 走看看