• 观察者模式(订阅-发布者模式)


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

      

  • 相关阅读:
    CR, LF, CR/LF区别与关系
    利用 jQuery 克隆 Object
    【2015】网易前端面经
    前端架构:Angular与requirejs集成实践
    高质量代码之HTML、CSS篇
    【转】requirejs简单入门
    2014搜狗前端面经【B事业部】
    2014小型公司前端面经
    【转】对象创建模式
    2014搜狗前端面经【A事业部】
  • 原文地址:https://www.cnblogs.com/zhaodesheng/p/10956149.html
Copyright © 2020-2023  润新知