Egret开发笔记[六]:循环执行管理器

有些游戏状态要随着时间的变化而变化,比如:每分钟提醒玩家充值…这个功能…
一个单例完美解决
思想: 将需要执行的方法注册进来,每隔一段时间,执行一个或者几个方法.

class LoopExecuteManager {
	private _dic:{[key:string]:{fun:()=>void,caller:any}};
	private _list:{fun:()=>void,caller:any}[];

	private _timer:egret.Timer;

	private _curIndex:number = 0;

	private _mainSwitch:boolean = false;

	public constructor() {
		this._dic = {};
		this._list = [];
		this.initTimer();
	}
	/*
	*外部主要调用此方法进行注册,把需要循环执行的方法注册进来
	*@parm key 键
	*@parm fun 需要循环执行的方法
	*@parm caller 作用域
	*/
	register(key:string,fun:()=>void,caller:any):void {
		let o = {fun:fun,caller:caller}
		this._dic[key] = o;
		this._list.push(o);
		this.updateTimer();
	}

	unregister(key:string):void {
		let o = this._dic[key];
		let index:number = this._list.indexOf(o);
		if(index >= 0) {
			this._list.splice(index,1);
		}
		delete this._dic[key];
		this.updateTimer();
	}

	/**
	 * 根据列表长度调整执行间隔,列表长度为0就停止时间器
	 */
	private updateTimer():void {
		if(this._mainSwitch == false) {
			if(this._timer.running) {
				this._timer.stop();
			}
			return;
		}
		if(this._list.length == 0) {
			if(this._timer.running) {
				this._timer.stop();
			}
		}else{
			if(!this._timer.running) {
				this._timer.start();
			}
			this._timer.delay = parseInt((8000/this._list.length).toString());
		}
	}

	private initTimer():void {
		var defaultDelay:number = 1000;
		this._timer = new egret.Timer(defaultDelay);
		this._timer.addEventListener(egret.TimerEvent.TIMER,this.onTimer,this);
	}

	private onTimer(e:egret.TimerEvent):void {
		if(this._list.length == 0) return;
		let fun = this._list[this._curIndex].fun;
		let caller = this._list[this._curIndex].caller;
		fun.call(caller);

		this._curIndex++;
		if(this._curIndex >= this._list.length) {
			this._curIndex = 0;
		}
	}

	start():void {
		this._mainSwitch = true;
		this.updateTimer();
	}

	stop():void {
		this._mainSwitch = false;
		this.updateTimer();
	}

	//-----------------------------------------------------------------
	private static _inst:LoopExecuteManager;
	static get inst():LoopExecuteManager {
		if(LoopExecuteManager._inst == null) {
			LoopExecuteManager._inst = new LoopExecuteManager();
		}
		return LoopExecuteManager._inst;
	}
}

你可能感兴趣的:(Egret学习笔记)