欢迎关注得胜的git仓库

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

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

  

posted on 2019-05-31 16:49  web得胜  阅读(178)  评论(0)    收藏  举报

导航

感谢观看web得胜的博客,如果您觉得对你有帮助,请点赞支持一下哦~。发现问题请留言指正,谢谢!