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

  

相关文章: